blob: be3abbd925c7fd5f77c210c32fa0f628ff2cb650 [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
Nick Lewyckyfb643e42009-02-03 07:13:24 +000047using namespace llvm;
Teresa Johnson9ba95f92016-08-11 14:58:12 +000048using namespace lto;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000049
Teresa Johnsoncb15b732015-12-16 16:34:06 +000050static ld_plugin_status discard_message(int level, const char *format, ...) {
51 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
52 // callback in the transfer vector. This should never be called.
53 abort();
54}
55
56static ld_plugin_release_input_file release_input_file = nullptr;
57static ld_plugin_get_input_file get_input_file = nullptr;
58static ld_plugin_message message = discard_message;
59
Nick Lewyckyfb643e42009-02-03 07:13:24 +000060namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000061struct claimed_file {
62 void *handle;
Teresa Johnson683abe72016-05-26 01:46:41 +000063 void *leader_handle;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000064 std::vector<ld_plugin_symbol> syms;
Teresa Johnson683abe72016-05-26 01:46:41 +000065 off_t filesize;
66 std::string name;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000067};
Rafael Espindolacaabe222015-12-10 14:19:35 +000068
Teresa Johnsoncb15b732015-12-16 16:34:06 +000069/// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
70struct PluginInputFile {
Teresa Johnson031bed22015-12-16 21:37:48 +000071 void *Handle;
Teresa Johnson7cffaf32016-03-04 17:06:02 +000072 std::unique_ptr<ld_plugin_input_file> File;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000073
Teresa Johnson031bed22015-12-16 21:37:48 +000074 PluginInputFile(void *Handle) : Handle(Handle) {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000075 File = llvm::make_unique<ld_plugin_input_file>();
76 if (get_input_file(Handle, File.get()) != LDPS_OK)
Teresa Johnsoncb15b732015-12-16 16:34:06 +000077 message(LDPL_FATAL, "Failed to get file information");
78 }
79 ~PluginInputFile() {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000080 // File would have been reset to nullptr if we moved this object
81 // to a new owner.
82 if (File)
83 if (release_input_file(Handle) != LDPS_OK)
84 message(LDPL_FATAL, "Failed to release file information");
Teresa Johnsoncb15b732015-12-16 16:34:06 +000085 }
Teresa Johnson7cffaf32016-03-04 17:06:02 +000086
87 ld_plugin_input_file &file() { return *File; }
88
89 PluginInputFile(PluginInputFile &&RHS) = default;
90 PluginInputFile &operator=(PluginInputFile &&RHS) = default;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000091};
92
Rafael Espindolacaabe222015-12-10 14:19:35 +000093struct ResolutionInfo {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000094 bool CanOmitFromDynSym = true;
95 bool DefaultVisibility = true;
Rafael Espindolacaabe222015-12-10 14:19:35 +000096};
Teresa Johnson7cffaf32016-03-04 17:06:02 +000097
Nick Lewyckyfb643e42009-02-03 07:13:24 +000098}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000099
Rafael Espindola176e6642014-07-29 21:46:05 +0000100static ld_plugin_add_symbols add_symbols = nullptr;
101static ld_plugin_get_symbols get_symbols = nullptr;
102static ld_plugin_add_input_file add_input_file = nullptr;
103static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
104static ld_plugin_get_view get_view = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000105static bool IsExecutable = false;
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000106static Optional<Reloc::Model> RelocationModel = None;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000107static std::string output_name = "";
108static std::list<claimed_file> Modules;
Teresa Johnson683abe72016-05-26 01:46:41 +0000109static DenseMap<int, void *> FDToLeaderHandle;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000110static StringMap<ResolutionInfo> ResInfo;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000111static std::vector<std::string> Cleanup;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000112
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000113namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000114 enum OutputType {
115 OT_NORMAL,
116 OT_DISABLE,
117 OT_BC_ONLY,
118 OT_SAVE_TEMPS
119 };
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000120 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000121 static unsigned OptLevel = 2;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000122 // Default parallelism of 0 used to indicate that user did not specify.
123 // Actual parallelism default value depends on implementation.
Teresa Johnsonec544c52016-10-19 17:35:01 +0000124 // Currently only affects ThinLTO, where the default is
125 // llvm::heavyweight_hardware_concurrency.
Teresa Johnsona9f65552016-03-04 16:36:06 +0000126 static unsigned Parallelism = 0;
Teresa Johnson896fee22016-09-23 20:35:19 +0000127 // Default regular LTO codegen parallelism (number of partitions).
128 static unsigned ParallelCodeGenParallelismLevel = 1;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000129#ifdef NDEBUG
130 static bool DisableVerify = true;
131#else
132 static bool DisableVerify = false;
133#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000134 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000135 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000136 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000137 static std::string mcpu;
Teresa Johnson403a7872015-10-04 14:33:43 +0000138 // When the thinlto plugin option is specified, only read the function
139 // the information from intermediate files and write a combined
140 // global index for the ThinLTO backends.
141 static bool thinlto = false;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000142 // If false, all ThinLTO backend compilations through code gen are performed
143 // using multiple threads in the gold-plugin, before handing control back to
Teresa Johnson84174c32016-05-10 13:48:23 +0000144 // gold. If true, write individual backend index files which reflect
145 // the import decisions, and exit afterwards. The assumption is
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000146 // that the build system will launch the backend processes.
147 static bool thinlto_index_only = false;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000148 // If non-empty, holds the name of a file in which to write the list of
149 // oject files gold selected for inclusion in the link after symbol
150 // resolution (i.e. they had selected symbols). This will only be non-empty
151 // in the thinlto_index_only case. It is used to identify files, which may
152 // have originally been within archive libraries specified via
153 // --start-lib/--end-lib pairs, that should be included in the final
154 // native link process (since intervening function importing and inlining
155 // may change the symbol resolution detected in the final link and which
156 // files to include out of --start-lib/--end-lib libraries as a result).
157 static std::string thinlto_linked_objects_file;
Teresa Johnson8570fe42016-05-10 15:54:09 +0000158 // If true, when generating individual index files for distributed backends,
159 // also generate a "${bitcodefile}.imports" file at the same location for each
160 // bitcode file, listing the files it imports from in plain text. This is to
161 // support distributed build file staging.
162 static bool thinlto_emit_imports_files = false;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000163 // Option to control where files for a distributed backend (the individual
164 // index files and optional imports files) are created.
165 // If specified, expects a string of the form "oldprefix:newprefix", and
166 // instead of generating these files in the same directory path as the
167 // corresponding bitcode file, will use a path formed by replacing the
168 // bitcode file's path prefix matching oldprefix with newprefix.
169 static std::string thinlto_prefix_replace;
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000170 // Option to control the name of modules encoded in the individual index
171 // files for a distributed backend. This enables the use of minimized
172 // bitcode files for the thin link, assuming the name of the full bitcode
173 // file used in the backend differs just in some part of the file suffix.
174 // If specified, expects a string of the form "oldsuffix:newsuffix".
175 static std::string thinlto_object_suffix_replace;
Teresa Johnson57891a52016-08-24 15:11:47 +0000176 // Optional path to a directory for caching ThinLTO objects.
177 static std::string cache_dir;
Yi Kongbb4b4ee2017-09-18 23:24:55 +0000178 // Optional pruning policy for ThinLTO caches.
179 static std::string cache_policy;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000180 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000181 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000182 // as plugin exclusive to pass to the code generator.
Rafael Espindola125b9242014-07-29 19:17:44 +0000183 static std::vector<const char *> extra;
Dehao Chen27978002016-12-16 16:48:46 +0000184 // Sample profile file path
185 static std::string sample_profile;
Sean Fertiledf8d9982017-10-05 01:48:42 +0000186 // New pass manager
187 static bool new_pass_manager = false;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000188
Nick Lewycky7282dd72015-08-05 21:16:02 +0000189 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000190 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000191 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000192 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000193 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000194
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000195 if (opt.startswith("mcpu=")) {
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000196 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000197 } else if (opt.startswith("extra-library-path=")) {
198 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000199 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000200 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000201 } else if (opt.startswith("obj-path=")) {
202 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000203 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000204 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000205 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000206 TheOutputType = OT_SAVE_TEMPS;
207 } else if (opt == "disable-output") {
208 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000209 } else if (opt == "thinlto") {
210 thinlto = true;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000211 } else if (opt == "thinlto-index-only") {
212 thinlto_index_only = true;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000213 } else if (opt.startswith("thinlto-index-only=")) {
214 thinlto_index_only = true;
215 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
Teresa Johnson8570fe42016-05-10 15:54:09 +0000216 } else if (opt == "thinlto-emit-imports-files") {
217 thinlto_emit_imports_files = true;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000218 } else if (opt.startswith("thinlto-prefix-replace=")) {
219 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000220 if (thinlto_prefix_replace.find(';') == std::string::npos)
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000221 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000222 } else if (opt.startswith("thinlto-object-suffix-replace=")) {
223 thinlto_object_suffix_replace =
224 opt.substr(strlen("thinlto-object-suffix-replace="));
225 if (thinlto_object_suffix_replace.find(';') == std::string::npos)
226 message(LDPL_FATAL,
227 "thinlto-object-suffix-replace expects 'old;new' format");
Teresa Johnson57891a52016-08-24 15:11:47 +0000228 } else if (opt.startswith("cache-dir=")) {
229 cache_dir = opt.substr(strlen("cache-dir="));
Yi Kongbb4b4ee2017-09-18 23:24:55 +0000230 } else if (opt.startswith("cache-policy=")) {
231 cache_policy = opt.substr(strlen("cache-policy="));
Peter Collingbourne070843d2015-03-19 22:01:00 +0000232 } else if (opt.size() == 2 && opt[0] == 'O') {
233 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000234 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000235 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000236 } else if (opt.startswith("jobs=")) {
237 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
238 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson896fee22016-09-23 20:35:19 +0000239 } else if (opt.startswith("lto-partitions=")) {
240 if (opt.substr(strlen("lto-partitions="))
241 .getAsInteger(10, ParallelCodeGenParallelismLevel))
242 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000243 } else if (opt == "disable-verify") {
244 DisableVerify = true;
Dehao Chen27978002016-12-16 16:48:46 +0000245 } else if (opt.startswith("sample-profile=")) {
246 sample_profile= opt.substr(strlen("sample-profile="));
Sean Fertiledf8d9982017-10-05 01:48:42 +0000247 } else if (opt == "new-pass-manager") {
248 new_pass_manager = true;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000249 } else {
250 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000251 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
252 // add that.
253 if (extra.empty())
254 extra.push_back("LLVMgold");
255
Rafael Espindola125b9242014-07-29 19:17:44 +0000256 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000257 }
258 }
259}
260
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000261static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
262 int *claimed);
263static ld_plugin_status all_symbols_read_hook(void);
264static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000265
266extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
267ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000268 InitializeAllTargetInfos();
269 InitializeAllTargets();
270 InitializeAllTargetMCs();
271 InitializeAllAsmParsers();
272 InitializeAllAsmPrinters();
273
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000274 // We're given a pointer to the first transfer vector. We read through them
275 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
276 // contain pointers to functions that we need to call to register our own
277 // hooks. The others are addresses of functions we can use to call into gold
278 // for services.
279
280 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000281 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000282
283 for (; tv->tv_tag != LDPT_NULL; ++tv) {
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000284 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
285 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
286 // header.
287 switch (static_cast<int>(tv->tv_tag)) {
288 case LDPT_OUTPUT_NAME:
289 output_name = tv->tv_u.tv_string;
290 break;
291 case LDPT_LINKER_OUTPUT:
292 switch (tv->tv_u.tv_val) {
293 case LDPO_REL: // .o
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000294 IsExecutable = false;
295 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000296 case LDPO_DYN: // .so
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000297 IsExecutable = false;
298 RelocationModel = Reloc::PIC_;
299 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000300 case LDPO_PIE: // position independent executable
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000301 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000302 RelocationModel = Reloc::PIC_;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000303 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000304 case LDPO_EXEC: // .exe
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000305 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000306 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000307 break;
308 default:
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000309 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
310 return LDPS_ERR;
311 }
312 break;
313 case LDPT_OPTION:
314 options::process_plugin_option(tv->tv_u.tv_string);
315 break;
316 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
317 ld_plugin_register_claim_file callback;
318 callback = tv->tv_u.tv_register_claim_file;
319
320 if (callback(claim_file_hook) != LDPS_OK)
321 return LDPS_ERR;
322
323 registeredClaimFile = true;
324 } break;
325 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
326 ld_plugin_register_all_symbols_read callback;
327 callback = tv->tv_u.tv_register_all_symbols_read;
328
329 if (callback(all_symbols_read_hook) != LDPS_OK)
330 return LDPS_ERR;
331
332 RegisteredAllSymbolsRead = true;
333 } break;
334 case LDPT_REGISTER_CLEANUP_HOOK: {
335 ld_plugin_register_cleanup callback;
336 callback = tv->tv_u.tv_register_cleanup;
337
338 if (callback(cleanup_hook) != LDPS_OK)
339 return LDPS_ERR;
340 } break;
341 case LDPT_GET_INPUT_FILE:
342 get_input_file = tv->tv_u.tv_get_input_file;
343 break;
344 case LDPT_RELEASE_INPUT_FILE:
345 release_input_file = tv->tv_u.tv_release_input_file;
346 break;
347 case LDPT_ADD_SYMBOLS:
348 add_symbols = tv->tv_u.tv_add_symbols;
349 break;
350 case LDPT_GET_SYMBOLS_V2:
351 // Do not override get_symbols_v3 with get_symbols_v2.
352 if (!get_symbols)
353 get_symbols = tv->tv_u.tv_get_symbols;
354 break;
355 case LDPT_GET_SYMBOLS_V3:
356 get_symbols = tv->tv_u.tv_get_symbols;
357 break;
358 case LDPT_ADD_INPUT_FILE:
359 add_input_file = tv->tv_u.tv_add_input_file;
360 break;
361 case LDPT_SET_EXTRA_LIBRARY_PATH:
362 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
363 break;
364 case LDPT_GET_VIEW:
365 get_view = tv->tv_u.tv_get_view;
366 break;
367 case LDPT_MESSAGE:
368 message = tv->tv_u.tv_message;
369 break;
370 default:
371 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000372 }
373 }
374
Rafael Espindolae08484d2009-02-18 08:30:15 +0000375 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000376 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000377 return LDPS_ERR;
378 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000379 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000380 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000381 return LDPS_ERR;
382 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000383
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000384 if (!RegisteredAllSymbolsRead)
385 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000386
Rafael Espindola33466a72014-08-21 20:28:55 +0000387 if (!get_input_file) {
388 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
389 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000390 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000391 if (!release_input_file) {
Marianne Mailhot-Sarrasina5a750e2016-03-30 12:20:53 +0000392 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
Rafael Espindola33466a72014-08-21 20:28:55 +0000393 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000394 }
395
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000396 return LDPS_OK;
397}
398
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000399static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000400 std::string ErrStorage;
401 {
402 raw_string_ostream OS(ErrStorage);
403 DiagnosticPrinterRawOStream DP(OS);
404 DI.print(DP);
405 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000406 ld_plugin_level Level;
407 switch (DI.getSeverity()) {
408 case DS_Error:
409 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
410 ErrStorage.c_str());
Rafael Espindola503f8832015-03-02 19:08:03 +0000411 case DS_Warning:
412 Level = LDPL_WARNING;
413 break;
414 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000415 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000416 Level = LDPL_INFO;
417 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000418 }
419 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000420}
421
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000422static void check(Error E, std::string Msg = "LLVM gold plugin") {
Mehdi Amini48f29602016-11-11 06:04:30 +0000423 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000424 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
425 return Error::success();
426 });
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000427}
428
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000429template <typename T> static T check(Expected<T> E) {
430 if (E)
431 return std::move(*E);
432 check(E.takeError());
433 return T();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000434}
435
Rafael Espindolae54d8212014-07-06 14:31:22 +0000436/// Called by gold to see whether this file is one that our plugin can handle.
437/// We'll try to open it and register all the symbols with add_symbol if
438/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000439static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
440 int *claimed) {
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000441 MemoryBufferRef BufferRef;
442 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000443 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000444 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000445 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000446 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000447 return LDPS_ERR;
448 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000449 BufferRef =
450 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000451 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000452 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000453 // Gold has found what might be IR part-way inside of a file, such as
454 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000455 if (file->offset) {
456 offset = file->offset;
457 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000458 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
459 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
460 offset);
461 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000462 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000463 return LDPS_ERR;
464 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000465 Buffer = std::move(BufferOrErr.get());
466 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000467 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000468
Rafael Espindola6c472e52014-07-29 20:46:19 +0000469 *claimed = 1;
470
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000471 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
472 if (!ObjOrErr) {
473 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
474 std::error_code EC = EI.convertToErrorCode();
475 if (EC == object::object_error::invalid_file_type ||
476 EC == object::object_error::bitcode_section_not_found)
477 *claimed = 0;
478 else
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000479 message(LDPL_FATAL,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000480 "LLVM gold plugin has failed to create LTO module: %s",
481 EI.message().c_str());
482 });
483
484 return *claimed ? LDPS_ERR : LDPS_OK;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000485 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000486
487 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000488
Dehao Chen396f6242017-07-10 15:31:53 +0000489 Modules.emplace_back();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000490 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000491
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000492 cf.handle = file->handle;
Teresa Johnson683abe72016-05-26 01:46:41 +0000493 // Keep track of the first handle for each file descriptor, since there are
494 // multiple in the case of an archive. This is used later in the case of
495 // ThinLTO parallel backends to ensure that each file is only opened and
496 // released once.
497 auto LeaderHandle =
498 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
499 cf.leader_handle = LeaderHandle->second;
500 // Save the filesize since for parallel ThinLTO backends we can only
501 // invoke get_input_file once per archive (only for the leader handle).
502 cf.filesize = file->filesize;
503 // In the case of an archive library, all but the first member must have a
504 // non-zero offset, which we can append to the file name to obtain a
505 // unique name.
506 cf.name = file->name;
507 if (file->offset)
508 cf.name += ".llvm." + std::to_string(file->offset) + "." +
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000509 sys::path::filename(Obj->getSourceFileName()).str();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000510
Rafael Espindola33466a72014-08-21 20:28:55 +0000511 for (auto &Sym : Obj->symbols()) {
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000512 cf.syms.push_back(ld_plugin_symbol());
513 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000514 sym.version = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000515 StringRef Name = Sym.getName();
516 sym.name = strdup(Name.str().c_str());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000517
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000518 ResolutionInfo &Res = ResInfo[Name];
Rafael Espindola33466a72014-08-21 20:28:55 +0000519
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000520 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000521
Rafael Espindola33466a72014-08-21 20:28:55 +0000522 sym.visibility = LDPV_DEFAULT;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000523 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
524 if (Vis != GlobalValue::DefaultVisibility)
525 Res.DefaultVisibility = false;
526 switch (Vis) {
527 case GlobalValue::DefaultVisibility:
528 break;
529 case GlobalValue::HiddenVisibility:
530 sym.visibility = LDPV_HIDDEN;
531 break;
532 case GlobalValue::ProtectedVisibility:
533 sym.visibility = LDPV_PROTECTED;
534 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000535 }
536
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000537 if (Sym.isUndefined()) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000538 sym.def = LDPK_UNDEF;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000539 if (Sym.isWeak())
Rafael Espindola56548522009-04-24 16:55:21 +0000540 sym.def = LDPK_WEAKUNDEF;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000541 } else if (Sym.isCommon())
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000542 sym.def = LDPK_COMMON;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000543 else if (Sym.isWeak())
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000544 sym.def = LDPK_WEAKDEF;
545 else
Rafael Espindola33466a72014-08-21 20:28:55 +0000546 sym.def = LDPK_DEF;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000547
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000548 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000549 sym.comdat_key = nullptr;
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000550 int CI = Sym.getComdatIndex();
Rafael Espindola79121102016-10-25 12:02:03 +0000551 if (CI != -1) {
552 StringRef C = Obj->getComdatTable()[CI];
Rafael Espindola62382c92016-10-17 18:51:02 +0000553 sym.comdat_key = strdup(C.str().c_str());
Rafael Espindola79121102016-10-25 12:02:03 +0000554 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000555
556 sym.resolution = LDPR_UNKNOWN;
557 }
558
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000559 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000560 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000561 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000562 return LDPS_ERR;
563 }
564 }
565
566 return LDPS_OK;
567}
568
Rafael Espindola538c9a82014-12-23 18:18:37 +0000569static void freeSymName(ld_plugin_symbol &Sym) {
570 free(Sym.name);
571 free(Sym.comdat_key);
572 Sym.name = nullptr;
573 Sym.comdat_key = nullptr;
574}
575
Teresa Johnsona9f65552016-03-04 16:36:06 +0000576/// Helper to get a file's symbols and a view into it via gold callbacks.
577static const void *getSymbolsAndView(claimed_file &F) {
Benjamin Kramer39988a02016-03-08 14:02:46 +0000578 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000579 if (status == LDPS_NO_SYMS)
580 return nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000581
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000582 if (status != LDPS_OK)
Teresa Johnson403a7872015-10-04 14:33:43 +0000583 message(LDPL_FATAL, "Failed to get symbol information");
584
585 const void *View;
586 if (get_view(F.handle, &View) != LDPS_OK)
587 message(LDPL_FATAL, "Failed to get a view of file");
588
Teresa Johnsona9f65552016-03-04 16:36:06 +0000589 return View;
590}
591
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000592/// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
593/// \p NewSuffix strings, if it was specified.
594static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
595 std::string &NewSuffix) {
596 assert(options::thinlto_object_suffix_replace.empty() ||
597 options::thinlto_object_suffix_replace.find(";") != StringRef::npos);
598 StringRef SuffixReplace = options::thinlto_object_suffix_replace;
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000599 std::tie(OldSuffix, NewSuffix) = SuffixReplace.split(';');
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000600}
601
602/// Given the original \p Path to an output file, replace any filename
603/// suffix matching \p OldSuffix with \p NewSuffix.
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000604static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
605 StringRef NewSuffix) {
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000606 if (OldSuffix.empty() && NewSuffix.empty())
607 return Path;
608 StringRef NewPath = Path;
609 NewPath.consume_back(OldSuffix);
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000610 std::string NewNewPath = NewPath;
611 NewNewPath += NewSuffix;
612 return NewNewPath;
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000613}
614
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000615// Returns true if S is valid as a C language identifier.
616static bool isValidCIdentifier(StringRef S) {
George Rimar3040da02017-10-04 11:00:30 +0000617 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
618 std::all_of(S.begin() + 1, S.end(),
619 [](char C) { return C == '_' || isAlnum(C); });
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000620}
621
Eugene Leviant746f1522017-12-15 09:18:21 +0000622static bool isUndefined(ld_plugin_symbol &Sym) {
623 return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
624}
625
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000626static void addModule(LTO &Lto, claimed_file &F, const void *View,
627 StringRef Filename) {
628 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
629 Filename);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000630 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000631
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000632 if (!ObjOrErr)
Peter Collingbourne10039c02014-09-18 21:28:49 +0000633 message(LDPL_FATAL, "Could not read bitcode from file : %s",
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000634 toString(ObjOrErr.takeError()).c_str());
Peter Collingbourne10039c02014-09-18 21:28:49 +0000635
Rafael Espindola527e8462014-12-09 16:13:59 +0000636 unsigned SymNum = 0;
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000637 std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
638 auto InputFileSyms = Input->symbols();
639 assert(InputFileSyms.size() == F.syms.size());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000640 std::vector<SymbolResolution> Resols(F.syms.size());
Peter Collingbourne07586442016-09-14 02:55:16 +0000641 for (ld_plugin_symbol &Sym : F.syms) {
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000642 const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
Peter Collingbourne07586442016-09-14 02:55:16 +0000643 SymbolResolution &R = Resols[SymNum++];
Rafael Espindola527e8462014-12-09 16:13:59 +0000644
Rafael Espindola33466a72014-08-21 20:28:55 +0000645 ld_plugin_symbol_resolution Resolution =
646 (ld_plugin_symbol_resolution)Sym.resolution;
647
Rafael Espindolacaabe222015-12-10 14:19:35 +0000648 ResolutionInfo &Res = ResInfo[Sym.name];
Rafael Espindola890db272014-09-09 20:08:22 +0000649
Rafael Espindola33466a72014-08-21 20:28:55 +0000650 switch (Resolution) {
651 case LDPR_UNKNOWN:
652 llvm_unreachable("Unexpected resolution");
653
654 case LDPR_RESOLVED_IR:
655 case LDPR_RESOLVED_EXEC:
656 case LDPR_RESOLVED_DYN:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000657 case LDPR_PREEMPTED_IR:
658 case LDPR_PREEMPTED_REG:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000659 case LDPR_UNDEF:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000660 break;
661
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000662 case LDPR_PREVAILING_DEF_IRONLY:
Eugene Leviant746f1522017-12-15 09:18:21 +0000663 R.Prevailing = !isUndefined(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000664 break;
Teresa Johnsonf99573b2016-08-11 12:56:40 +0000665
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000666 case LDPR_PREVAILING_DEF:
Eugene Leviant746f1522017-12-15 09:18:21 +0000667 R.Prevailing = !isUndefined(Sym);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000668 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000669 break;
670
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000671 case LDPR_PREVAILING_DEF_IRONLY_EXP:
Eugene Leviant746f1522017-12-15 09:18:21 +0000672 R.Prevailing = !isUndefined(Sym);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000673 if (!Res.CanOmitFromDynSym)
674 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000675 break;
676 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000677
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000678 // If the symbol has a C identifier section name, we need to mark
679 // it as visible to a regular object so that LTO will keep it around
680 // to ensure the linker generates special __start_<secname> and
681 // __stop_<secname> symbols which may be used elsewhere.
682 if (isValidCIdentifier(InpSym.getSectionName()))
683 R.VisibleToRegularObj = true;
684
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000685 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
686 (IsExecutable || !Res.DefaultVisibility))
687 R.FinalDefinitionInLinkageUnit = true;
688
Rafael Espindola538c9a82014-12-23 18:18:37 +0000689 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000690 }
691
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000692 check(Lto.add(std::move(Input), Resols),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000693 std::string("Failed to link module ") + F.name);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000694}
695
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000696static void recordFile(const std::string &Filename, bool TempOutFile) {
Teresa Johnsona9f65552016-03-04 16:36:06 +0000697 if (add_input_file(Filename.c_str()) != LDPS_OK)
698 message(LDPL_FATAL,
699 "Unable to add .o file to the link. File left behind in: %s",
700 Filename.c_str());
701 if (TempOutFile)
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000702 Cleanup.push_back(Filename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000703}
Rafael Espindola33466a72014-08-21 20:28:55 +0000704
Mehdi Amini970800e2016-08-17 06:23:09 +0000705/// Return the desired output filename given a base input name, a flag
706/// indicating whether a temp file should be generated, and an optional task id.
707/// The new filename generated is returned in \p NewFilename.
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000708static int getOutputFileName(StringRef InFilename, bool TempOutFile,
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000709 SmallString<128> &NewFilename, int TaskID) {
710 int FD = -1;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000711 if (TempOutFile) {
712 std::error_code EC =
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000713 sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000714 if (EC)
715 message(LDPL_FATAL, "Could not create temporary file: %s",
716 EC.message().c_str());
717 } else {
718 NewFilename = InFilename;
Peter Collingbourne6201d782017-01-26 02:07:05 +0000719 if (TaskID > 0)
Teresa Johnsona9f65552016-03-04 16:36:06 +0000720 NewFilename += utostr(TaskID);
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000721 std::error_code EC =
722 sys::fs::openFileForWrite(NewFilename, FD, sys::fs::F_None);
723 if (EC)
724 message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
725 EC.message().c_str());
Teresa Johnsona9f65552016-03-04 16:36:06 +0000726 }
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000727 return FD;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000728}
729
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000730/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
731/// \p NewPrefix strings, if it was specified.
732static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
733 std::string &NewPrefix) {
734 StringRef PrefixReplace = options::thinlto_prefix_replace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000735 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000736 std::tie(OldPrefix, NewPrefix) = PrefixReplace.split(';');
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000737}
738
Vitaly Buka59baf732018-01-30 21:19:26 +0000739static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000740 Config Conf;
741 ThinBackend Backend;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000742
743 Conf.CPU = options::mcpu;
744 Conf.Options = InitTargetOptionsFromCodeGenFlags();
745
746 // Disable the new X86 relax relocations since gold might not support them.
747 // FIXME: Check the gold version or add a new option to enable them.
748 Conf.Options.RelaxELFRelocations = false;
749
Davide Italiano557a0b32017-07-26 01:47:17 +0000750 // Enable function/data sections by default.
Davide Italiano756feb22017-07-25 23:32:50 +0000751 Conf.Options.FunctionSections = true;
Davide Italiano557a0b32017-07-26 01:47:17 +0000752 Conf.Options.DataSections = true;
Davide Italiano756feb22017-07-25 23:32:50 +0000753
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000754 Conf.MAttrs = MAttrs;
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000755 Conf.RelocModel = RelocationModel;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000756 Conf.DisableVerify = options::DisableVerify;
757 Conf.OptLevel = options::OptLevel;
Teresa Johnson896fee22016-09-23 20:35:19 +0000758 if (options::Parallelism)
759 Backend = createInProcessThinBackend(options::Parallelism);
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000760 if (options::thinlto_index_only) {
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000761 std::string OldPrefix, NewPrefix;
762 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000763 Backend = createWriteIndexesThinBackend(
764 OldPrefix, NewPrefix, options::thinlto_emit_imports_files,
Vitaly Buka59baf732018-01-30 21:19:26 +0000765 options::thinlto_linked_objects_file, OnIndexWrite);
Teresa Johnson84174c32016-05-10 13:48:23 +0000766 }
767
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000768 Conf.OverrideTriple = options::triple;
769 Conf.DefaultTriple = sys::getDefaultTargetTriple();
770
771 Conf.DiagHandler = diagnosticHandler;
772
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000773 switch (options::TheOutputType) {
774 case options::OT_NORMAL:
775 break;
776
777 case options::OT_DISABLE:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000778 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000779 break;
780
781 case options::OT_BC_ONLY:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000782 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000783 std::error_code EC;
784 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
785 if (EC)
786 message(LDPL_FATAL, "Failed to write the output file.");
Rafael Espindola6a86e252018-02-14 19:11:32 +0000787 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000788 return false;
789 };
790 break;
791
792 case options::OT_SAVE_TEMPS:
Mehdi Aminieccffad2016-08-18 00:12:33 +0000793 check(Conf.addSaveTemps(output_name + ".",
794 /* UseInputModulePath */ true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000795 break;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000796 }
797
Dehao Chen27978002016-12-16 16:48:46 +0000798 if (!options::sample_profile.empty())
799 Conf.SampleProfile = options::sample_profile;
800
Sean Fertiledf8d9982017-10-05 01:48:42 +0000801 // Use new pass manager if set in driver
802 Conf.UseNewPM = options::new_pass_manager;
803
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000804 return llvm::make_unique<LTO>(std::move(Conf), Backend,
Teresa Johnson896fee22016-09-23 20:35:19 +0000805 options::ParallelCodeGenParallelismLevel);
Teresa Johnson84174c32016-05-10 13:48:23 +0000806}
807
Teresa Johnson3f212b82016-09-21 19:12:05 +0000808// Write empty files that may be expected by a distributed build
809// system when invoked with thinlto_index_only. This is invoked when
810// the linker has decided not to include the given module in the
811// final link. Frequently the distributed build system will want to
812// confirm that all expected outputs are created based on all of the
813// modules provided to the linker.
Vitaly Buka769134d2018-02-16 23:38:22 +0000814// If SkipModule is true then .thinlto.bc should contain just
815// SkipModuleByDistributedBackend flag which requests distributed backend
816// to skip the compilation of the corresponding module and produce an empty
817// object file.
Vitaly Buka59baf732018-01-30 21:19:26 +0000818static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
819 const std::string &OldPrefix,
Vitaly Buka769134d2018-02-16 23:38:22 +0000820 const std::string &NewPrefix,
821 bool SkipModule) {
Teresa Johnson3f212b82016-09-21 19:12:05 +0000822 std::string NewModulePath =
823 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
824 std::error_code EC;
825 {
826 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
827 sys::fs::OpenFlags::F_None);
828 if (EC)
829 message(LDPL_FATAL, "Failed to write '%s': %s",
830 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
Vitaly Buka769134d2018-02-16 23:38:22 +0000831
832 if (SkipModule) {
833 ModuleSummaryIndex Index(false);
834 Index.setSkipModuleByDistributedBackend();
835 WriteIndexToFile(Index, OS, nullptr);
836 }
Teresa Johnson3f212b82016-09-21 19:12:05 +0000837 }
838 if (options::thinlto_emit_imports_files) {
839 raw_fd_ostream OS(NewModulePath + ".imports", EC,
840 sys::fs::OpenFlags::F_None);
841 if (EC)
842 message(LDPL_FATAL, "Failed to write '%s': %s",
843 (NewModulePath + ".imports").c_str(), EC.message().c_str());
844 }
845}
846
Rafael Espindolab6393292014-07-30 01:23:45 +0000847/// gold informs us that all symbols have been read. At this point, we use
848/// get_symbols to see if any of our definitions have been overridden by a
849/// native object file. Then, perform optimization and codegen.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000850static ld_plugin_status allSymbolsReadHook() {
Rafael Espindola33466a72014-08-21 20:28:55 +0000851 if (Modules.empty())
852 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000853
Teresa Johnsona9f65552016-03-04 16:36:06 +0000854 if (unsigned NumOpts = options::extra.size())
855 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
856
Teresa Johnson765941a2016-08-20 01:24:07 +0000857 // Map to own RAII objects that manage the file opening and releasing
858 // interfaces with gold. This is needed only for ThinLTO mode, since
859 // unlike regular LTO, where addModule will result in the opened file
860 // being merged into a new combined module, we need to keep these files open
861 // through Lto->run().
862 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
863
Vitaly Buka59baf732018-01-30 21:19:26 +0000864 // Owns string objects and tells if index file was already created.
865 StringMap<bool> ObjectToIndexFileState;
866
867 std::unique_ptr<LTO> Lto =
868 createLTO([&ObjectToIndexFileState](const std::string &Identifier) {
869 ObjectToIndexFileState[Identifier] = true;
870 });
Teresa Johnson403a7872015-10-04 14:33:43 +0000871
Teresa Johnson3f212b82016-09-21 19:12:05 +0000872 std::string OldPrefix, NewPrefix;
873 if (options::thinlto_index_only)
874 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
875
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000876 std::string OldSuffix, NewSuffix;
877 getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000878
Rafael Espindolad2aac572014-07-30 01:52:40 +0000879 for (claimed_file &F : Modules) {
Teresa Johnson765941a2016-08-20 01:24:07 +0000880 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
881 HandleToInputFile.insert(std::make_pair(
882 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000883 // In case we are thin linking with a minimized bitcode file, ensure
884 // the module paths encoded in the index reflect where the backends
885 // will locate the full bitcode files for compiling/importing.
886 std::string Identifier =
887 getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
Vitaly Buka59baf732018-01-30 21:19:26 +0000888 auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000889 assert(ObjFilename.second);
Vitaly Buka59baf732018-01-30 21:19:26 +0000890 if (const void *View = getSymbolsAndView(F))
891 addModule(*Lto, F, View, ObjFilename.first->first());
Vitaly Buka769134d2018-02-16 23:38:22 +0000892 else if (options::thinlto_index_only) {
893 ObjFilename.first->second = true;
894 writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
895 /* SkipModule */ true);
896 }
Rafael Espindola77b6d012010-06-14 21:20:52 +0000897 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000898
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000899 SmallString<128> Filename;
Mehdi Amini970800e2016-08-17 06:23:09 +0000900 // Note that getOutputFileName will append a unique ID for each task
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000901 if (!options::obj_path.empty())
902 Filename = options::obj_path;
903 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
904 Filename = output_name + ".o";
905 bool SaveTemps = !Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000906
Peter Collingbourne6201d782017-01-26 02:07:05 +0000907 size_t MaxTasks = Lto->getMaxTasks();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000908 std::vector<uintptr_t> IsTemporary(MaxTasks);
909 std::vector<SmallString<128>> Filenames(MaxTasks);
910
Peter Collingbourne80186a52016-09-23 21:33:43 +0000911 auto AddStream =
912 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
913 IsTemporary[Task] = !SaveTemps;
Vitaly Buka769134d2018-02-16 23:38:22 +0000914 int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000915 Filenames[Task], Task);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000916 return llvm::make_unique<lto::NativeObjectStream>(
917 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000918 };
919
Teresa Johnsona344fd32018-02-20 20:21:53 +0000920 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
Teresa Johnsonb145cca2018-02-20 19:51:30 +0000921 *AddStream(Task)->OS << MB->getBuffer();
Peter Collingbourne128423f2017-03-17 00:34:07 +0000922 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000923
924 NativeObjectCache Cache;
925 if (!options::cache_dir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000926 Cache = check(localCache(options::cache_dir, AddBuffer));
Peter Collingbourne80186a52016-09-23 21:33:43 +0000927
928 check(Lto->run(AddStream, Cache));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000929
Vitaly Buka59baf732018-01-30 21:19:26 +0000930 // Write empty output files that may be expected by the distributed build
931 // system.
932 if (options::thinlto_index_only)
933 for (auto &Identifier : ObjectToIndexFileState)
934 if (!Identifier.getValue())
935 writeEmptyDistributedBuildOutputs(Identifier.getKey(), OldPrefix,
Vitaly Buka769134d2018-02-16 23:38:22 +0000936 NewPrefix, /* SkipModule */ false);
Vitaly Buka59baf732018-01-30 21:19:26 +0000937
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000938 if (options::TheOutputType == options::OT_DISABLE ||
939 options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000940 return LDPS_OK;
941
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000942 if (options::thinlto_index_only) {
Teresa Johnson95597ae2017-02-02 17:33:53 +0000943 if (llvm::AreStatisticsEnabled())
944 llvm::PrintStatistics();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000945 cleanup_hook();
946 exit(0);
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000947 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000948
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000949 for (unsigned I = 0; I != MaxTasks; ++I)
950 if (!Filenames[I].empty())
951 recordFile(Filenames[I].str(), IsTemporary[I]);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000952
Rafael Espindolaef498152010-06-23 20:20:59 +0000953 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000954 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
955 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000956
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000957 return LDPS_OK;
958}
959
Rafael Espindola55b32542014-08-11 19:06:54 +0000960static ld_plugin_status all_symbols_read_hook(void) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000961 ld_plugin_status Ret = allSymbolsReadHook();
Rafael Espindola947bdb62014-11-25 20:52:49 +0000962 llvm_shutdown();
963
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000964 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000965 options::TheOutputType == options::OT_DISABLE) {
Davide Italiano289a43e2016-03-20 20:12:33 +0000966 if (options::TheOutputType == options::OT_DISABLE) {
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000967 // Remove the output file here since ld.bfd creates the output file
968 // early.
Davide Italiano289a43e2016-03-20 20:12:33 +0000969 std::error_code EC = sys::fs::remove(output_name);
970 if (EC)
971 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
972 EC.message().c_str());
973 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000974 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000975 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000976
977 return Ret;
978}
979
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000980static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000981 for (std::string &Name : Cleanup) {
982 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000983 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000984 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000985 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000986 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000987
Yi Kongbb4b4ee2017-09-18 23:24:55 +0000988 // Prune cache
989 if (!options::cache_policy.empty()) {
990 CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
991 pruneCache(options::cache_dir, policy);
992 }
993
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000994 return LDPS_OK;
995}