blob: 738cafa6cacf23d7623e96b67e738dd2951ede6d [file] [log] [blame]
Nick Lewycky3e62b2d2009-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 Johnson8ffb6b12017-02-02 17:33:53 +000015#include "llvm/ADT/Statistic.h"
Teresa Johnsona5479192016-11-11 05:34:58 +000016#include "llvm/Bitcode/BitcodeReader.h"
17#include "llvm/Bitcode/BitcodeWriter.h"
David Blaikie461bf522018-04-11 18:49:37 +000018#include "llvm/CodeGen/CommandFlags.inc"
Mehdi Aminif6071e12016-04-18 09:17:29 +000019#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
Rafael Espindola19f38682014-09-09 20:08:22 +000020#include "llvm/IR/Constants.h"
Rafael Espindola68016e02015-01-10 00:07:30 +000021#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson57b248a2016-08-24 15:11:47 +000022#include "llvm/LTO/Caching.h"
Teresa Johnsonbb83f892016-05-26 01:46:41 +000023#include "llvm/LTO/LTO.h"
Peter Collingbourne14ecedf2017-03-28 23:35:34 +000024#include "llvm/Object/Error.h"
Yi Kong74ae6062017-09-18 23:24:55 +000025#include "llvm/Support/CachePruning.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000026#include "llvm/Support/CommandLine.h"
Peter Collingbourne14ecedf2017-03-28 23:35:34 +000027#include "llvm/Support/FileSystem.h"
Rafael Espindola2fbbd7a2014-11-25 20:52:49 +000028#include "llvm/Support/ManagedStatic.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000029#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsona4863812016-05-17 14:45:30 +000030#include "llvm/Support/Path.h"
Rafael Espindola0b5745a2014-06-19 21:14:13 +000031#include "llvm/Support/TargetSelect.h"
Teresa Johnsona63df072015-12-09 19:45:55 +000032#include "llvm/Support/raw_ostream.h"
Nick Lewycky3e62b2d2009-02-03 07:13:24 +000033#include <list>
Teresa Johnson2d320e52016-08-11 14:58:12 +000034#include <map>
Chandler Carruth9f20a4c2014-01-13 08:04:33 +000035#include <plugin-api.h>
Teresa Johnson2d320e52016-08-11 14:58:12 +000036#include <string>
Rafael Espindolad5132f92014-06-12 17:38:55 +000037#include <system_error>
Benjamin Kramer14aae012016-05-27 14:27:24 +000038#include <utility>
Nick Lewycky3e62b2d2009-02-03 07:13:24 +000039#include <vector>
40
Sylvestre Ledru6a089db2014-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 Stepanovf0c747b2016-03-04 00:23:29 +000043#define LDPO_PIE 3
44
45#define LDPT_GET_SYMBOLS_V3 28
Sylvestre Ledru6a089db2014-02-11 17:30:18 +000046
Teresa Johnsonead87652018-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 Lewycky3e62b2d2009-02-03 07:13:24 +000051using namespace llvm;
Teresa Johnson2d320e52016-08-11 14:58:12 +000052using namespace lto;
Nick Lewycky3e62b2d2009-02-03 07:13:24 +000053
Teresa Johnsonead87652018-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 Johnson2c50df62015-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 Johnsonead87652018-03-14 13:26:18 +000068static ld_plugin_get_wrap_symbols get_wrap_symbols = nullptr;
Teresa Johnson2c50df62015-12-16 16:34:06 +000069
Nick Lewycky3e62b2d2009-02-03 07:13:24 +000070namespace {
Rafael Espindola8483dac2014-06-20 01:37:35 +000071struct claimed_file {
72 void *handle;
Teresa Johnsonbb83f892016-05-26 01:46:41 +000073 void *leader_handle;
Rafael Espindola8483dac2014-06-20 01:37:35 +000074 std::vector<ld_plugin_symbol> syms;
Teresa Johnsonbb83f892016-05-26 01:46:41 +000075 off_t filesize;
76 std::string name;
Rafael Espindola8483dac2014-06-20 01:37:35 +000077};
Rafael Espindolada513202015-12-10 14:19:35 +000078
Teresa Johnson2c50df62015-12-16 16:34:06 +000079/// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
80struct PluginInputFile {
Teresa Johnson5af13d72015-12-16 21:37:48 +000081 void *Handle;
Teresa Johnson2209e672016-03-04 17:06:02 +000082 std::unique_ptr<ld_plugin_input_file> File;
Teresa Johnson2c50df62015-12-16 16:34:06 +000083
Teresa Johnson5af13d72015-12-16 21:37:48 +000084 PluginInputFile(void *Handle) : Handle(Handle) {
Teresa Johnson2209e672016-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 Johnson2c50df62015-12-16 16:34:06 +000087 message(LDPL_FATAL, "Failed to get file information");
88 }
89 ~PluginInputFile() {
Teresa Johnson2209e672016-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 Johnson2c50df62015-12-16 16:34:06 +000095 }
Teresa Johnson2209e672016-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 Johnson2c50df62015-12-16 16:34:06 +0000101};
102
Rafael Espindolada513202015-12-10 14:19:35 +0000103struct ResolutionInfo {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000104 bool CanOmitFromDynSym = true;
105 bool DefaultVisibility = true;
Teresa Johnsonead87652018-03-14 13:26:18 +0000106 bool CanInline = true;
107 bool IsUsedInRegularObj = false;
Rafael Espindolada513202015-12-10 14:19:35 +0000108};
Teresa Johnson2209e672016-03-04 17:06:02 +0000109
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000110}
Rafael Espindola8483dac2014-06-20 01:37:35 +0000111
Rafael Espindola3c084732014-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 Johnson2d320e52016-08-11 14:58:12 +0000117static bool IsExecutable = false;
Bill Wendling0a4671b2018-07-12 20:35:58 +0000118static bool SplitSections = true;
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000119static Optional<Reloc::Model> RelocationModel = None;
Rafael Espindola8483dac2014-06-20 01:37:35 +0000120static std::string output_name = "";
121static std::list<claimed_file> Modules;
Teresa Johnsonbb83f892016-05-26 01:46:41 +0000122static DenseMap<int, void *> FDToLeaderHandle;
Rafael Espindolada513202015-12-10 14:19:35 +0000123static StringMap<ResolutionInfo> ResInfo;
Rafael Espindola8483dac2014-06-20 01:37:35 +0000124static std::vector<std::string> Cleanup;
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000125
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000126namespace options {
Rafael Espindolaf1ca1d42014-11-24 21:18:14 +0000127 enum OutputType {
128 OT_NORMAL,
129 OT_DISABLE,
130 OT_BC_ONLY,
Teresa Johnson02e82c32019-01-02 23:48:00 +0000131 OT_ASM_ONLY,
Rafael Espindolaf1ca1d42014-11-24 21:18:14 +0000132 OT_SAVE_TEMPS
133 };
Rafael Espindolaf1ca1d42014-11-24 21:18:14 +0000134 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne416d8ec2015-03-19 22:01:00 +0000135 static unsigned OptLevel = 2;
Teresa Johnson07943592016-03-04 16:36:06 +0000136 // Default parallelism of 0 used to indicate that user did not specify.
137 // Actual parallelism default value depends on implementation.
Teresa Johnson740d8712016-10-19 17:35:01 +0000138 // Currently only affects ThinLTO, where the default is
139 // llvm::heavyweight_hardware_concurrency.
Teresa Johnson07943592016-03-04 16:36:06 +0000140 static unsigned Parallelism = 0;
Teresa Johnson468ae9f2016-09-23 20:35:19 +0000141 // Default regular LTO codegen parallelism (number of partitions).
142 static unsigned ParallelCodeGenParallelismLevel = 1;
Teresa Johnson15c79f62015-09-16 18:06:45 +0000143#ifdef NDEBUG
144 static bool DisableVerify = true;
145#else
146 static bool DisableVerify = false;
147#endif
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000148 static std::string obj_path;
Rafael Espindola11f403c2010-06-23 20:20:59 +0000149 static std::string extra_library_path;
Rafael Espindolacbb170d2010-08-09 21:09:46 +0000150 static std::string triple;
Rafael Espindola2d643ef2010-08-11 00:15:13 +0000151 static std::string mcpu;
Teresa Johnsonb97baa52015-10-04 14:33:43 +0000152 // When the thinlto plugin option is specified, only read the function
153 // the information from intermediate files and write a combined
154 // global index for the ThinLTO backends.
155 static bool thinlto = false;
Teresa Johnson2209e672016-03-04 17:06:02 +0000156 // If false, all ThinLTO backend compilations through code gen are performed
157 // using multiple threads in the gold-plugin, before handing control back to
Teresa Johnson27af2052016-05-10 13:48:23 +0000158 // gold. If true, write individual backend index files which reflect
159 // the import decisions, and exit afterwards. The assumption is
Teresa Johnson2209e672016-03-04 17:06:02 +0000160 // that the build system will launch the backend processes.
161 static bool thinlto_index_only = false;
Teresa Johnson9493a842016-07-22 18:20:22 +0000162 // If non-empty, holds the name of a file in which to write the list of
163 // oject files gold selected for inclusion in the link after symbol
164 // resolution (i.e. they had selected symbols). This will only be non-empty
165 // in the thinlto_index_only case. It is used to identify files, which may
166 // have originally been within archive libraries specified via
167 // --start-lib/--end-lib pairs, that should be included in the final
168 // native link process (since intervening function importing and inlining
169 // may change the symbol resolution detected in the final link and which
170 // files to include out of --start-lib/--end-lib libraries as a result).
171 static std::string thinlto_linked_objects_file;
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000172 // If true, when generating individual index files for distributed backends,
173 // also generate a "${bitcodefile}.imports" file at the same location for each
174 // bitcode file, listing the files it imports from in plain text. This is to
175 // support distributed build file staging.
176 static bool thinlto_emit_imports_files = false;
Teresa Johnsona4863812016-05-17 14:45:30 +0000177 // Option to control where files for a distributed backend (the individual
178 // index files and optional imports files) are created.
179 // If specified, expects a string of the form "oldprefix:newprefix", and
180 // instead of generating these files in the same directory path as the
181 // corresponding bitcode file, will use a path formed by replacing the
182 // bitcode file's path prefix matching oldprefix with newprefix.
183 static std::string thinlto_prefix_replace;
Teresa Johnson08d0e942017-03-23 19:47:39 +0000184 // Option to control the name of modules encoded in the individual index
185 // files for a distributed backend. This enables the use of minimized
186 // bitcode files for the thin link, assuming the name of the full bitcode
187 // file used in the backend differs just in some part of the file suffix.
188 // If specified, expects a string of the form "oldsuffix:newsuffix".
189 static std::string thinlto_object_suffix_replace;
Teresa Johnson57b248a2016-08-24 15:11:47 +0000190 // Optional path to a directory for caching ThinLTO objects.
191 static std::string cache_dir;
Yi Kong74ae6062017-09-18 23:24:55 +0000192 // Optional pruning policy for ThinLTO caches.
193 static std::string cache_policy;
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000194 // Additional options to pass into the code generator.
Nick Lewyckyfc55def2010-06-03 17:10:17 +0000195 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000196 // as plugin exclusive to pass to the code generator.
Rafael Espindolad7a5d942014-07-29 19:17:44 +0000197 static std::vector<const char *> extra;
Dehao Chen7e436002016-12-16 16:48:46 +0000198 // Sample profile file path
199 static std::string sample_profile;
Sean Fertileabd8a852017-10-05 01:48:42 +0000200 // New pass manager
201 static bool new_pass_manager = false;
Teresa Johnson65834ee2018-04-05 03:16:57 +0000202 // Debug new pass manager
203 static bool debug_pass_manager = false;
Yunlian Jiangedd00e42018-04-13 05:03:28 +0000204 // Directory to store the .dwo files.
205 static std::string dwo_dir;
Florian Hahna2fbfc92018-04-20 10:18:36 +0000206 /// Statistics output filename.
207 static std::string stats_file;
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000208
Teresa Johnson48ba6662018-04-18 13:25:23 +0000209 // Optimization remarks filename and hotness options
210 static std::string OptRemarksFilename;
211 static bool OptRemarksWithHotness = false;
212
Nick Lewycky39879762015-08-05 21:16:02 +0000213 static void process_plugin_option(const char *opt_)
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000214 {
Rafael Espindola3c084732014-07-29 21:46:05 +0000215 if (opt_ == nullptr)
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000216 return;
Rafael Espindola6c809922010-06-07 16:45:22 +0000217 llvm::StringRef opt = opt_;
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000218
Teresa Johnson2d320e52016-08-11 14:58:12 +0000219 if (opt.startswith("mcpu=")) {
Rafael Espindola2d643ef2010-08-11 00:15:13 +0000220 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindola11f403c2010-06-23 20:20:59 +0000221 } else if (opt.startswith("extra-library-path=")) {
222 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola15af3872010-08-10 16:32:15 +0000223 } else if (opt.startswith("mtriple=")) {
Rafael Espindolacbb170d2010-08-09 21:09:46 +0000224 triple = opt.substr(strlen("mtriple="));
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000225 } else if (opt.startswith("obj-path=")) {
226 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindola6c809922010-06-07 16:45:22 +0000227 } else if (opt == "emit-llvm") {
Rafael Espindolaf1ca1d42014-11-24 21:18:14 +0000228 TheOutputType = OT_BC_ONLY;
Rafael Espindola25016f92014-10-29 23:54:45 +0000229 } else if (opt == "save-temps") {
Rafael Espindolaf1ca1d42014-11-24 21:18:14 +0000230 TheOutputType = OT_SAVE_TEMPS;
231 } else if (opt == "disable-output") {
232 TheOutputType = OT_DISABLE;
Teresa Johnson02e82c32019-01-02 23:48:00 +0000233 } else if (opt == "emit-asm") {
234 TheOutputType = OT_ASM_ONLY;
Teresa Johnsonb97baa52015-10-04 14:33:43 +0000235 } else if (opt == "thinlto") {
236 thinlto = true;
Teresa Johnson2209e672016-03-04 17:06:02 +0000237 } else if (opt == "thinlto-index-only") {
238 thinlto_index_only = true;
Teresa Johnson9493a842016-07-22 18:20:22 +0000239 } else if (opt.startswith("thinlto-index-only=")) {
240 thinlto_index_only = true;
241 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
Teresa Johnson4b05ce22016-05-10 15:54:09 +0000242 } else if (opt == "thinlto-emit-imports-files") {
243 thinlto_emit_imports_files = true;
Teresa Johnsona4863812016-05-17 14:45:30 +0000244 } else if (opt.startswith("thinlto-prefix-replace=")) {
245 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
Benjamin Kramerbf60ce02016-11-30 10:01:11 +0000246 if (thinlto_prefix_replace.find(';') == std::string::npos)
Reid Kleckner4e35fa52016-05-17 18:43:22 +0000247 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
Teresa Johnson08d0e942017-03-23 19:47:39 +0000248 } else if (opt.startswith("thinlto-object-suffix-replace=")) {
249 thinlto_object_suffix_replace =
250 opt.substr(strlen("thinlto-object-suffix-replace="));
251 if (thinlto_object_suffix_replace.find(';') == std::string::npos)
252 message(LDPL_FATAL,
253 "thinlto-object-suffix-replace expects 'old;new' format");
Teresa Johnson57b248a2016-08-24 15:11:47 +0000254 } else if (opt.startswith("cache-dir=")) {
255 cache_dir = opt.substr(strlen("cache-dir="));
Yi Kong74ae6062017-09-18 23:24:55 +0000256 } else if (opt.startswith("cache-policy=")) {
257 cache_policy = opt.substr(strlen("cache-policy="));
Peter Collingbourne416d8ec2015-03-19 22:01:00 +0000258 } else if (opt.size() == 2 && opt[0] == 'O') {
259 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne0a1d37b2015-09-01 20:40:22 +0000260 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne416d8ec2015-03-19 22:01:00 +0000261 OptLevel = opt[1] - '0';
Peter Collingbourne0a1d37b2015-09-01 20:40:22 +0000262 } else if (opt.startswith("jobs=")) {
263 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
264 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson468ae9f2016-09-23 20:35:19 +0000265 } else if (opt.startswith("lto-partitions=")) {
266 if (opt.substr(strlen("lto-partitions="))
267 .getAsInteger(10, ParallelCodeGenParallelismLevel))
268 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
Teresa Johnson15c79f62015-09-16 18:06:45 +0000269 } else if (opt == "disable-verify") {
270 DisableVerify = true;
Dehao Chen7e436002016-12-16 16:48:46 +0000271 } else if (opt.startswith("sample-profile=")) {
272 sample_profile= opt.substr(strlen("sample-profile="));
Sean Fertileabd8a852017-10-05 01:48:42 +0000273 } else if (opt == "new-pass-manager") {
274 new_pass_manager = true;
Teresa Johnson65834ee2018-04-05 03:16:57 +0000275 } else if (opt == "debug-pass-manager") {
276 debug_pass_manager = true;
Yunlian Jiangedd00e42018-04-13 05:03:28 +0000277 } else if (opt.startswith("dwo_dir=")) {
278 dwo_dir = opt.substr(strlen("dwo_dir="));
Teresa Johnson48ba6662018-04-18 13:25:23 +0000279 } else if (opt.startswith("opt-remarks-filename=")) {
280 OptRemarksFilename = opt.substr(strlen("opt-remarks-filename="));
281 } else if (opt == "opt-remarks-with-hotness") {
282 OptRemarksWithHotness = true;
Florian Hahna2fbfc92018-04-20 10:18:36 +0000283 } else if (opt.startswith("stats-file=")) {
284 stats_file = opt.substr(strlen("stats-file="));
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000285 } else {
286 // Save this option to pass to the code generator.
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000287 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
288 // add that.
289 if (extra.empty())
290 extra.push_back("LLVMgold");
291
Rafael Espindolad7a5d942014-07-29 19:17:44 +0000292 extra.push_back(opt_);
Viktor Kutuzov5c00b4a2009-10-28 18:55:55 +0000293 }
294 }
295}
296
Dan Gohmanf6920032010-04-16 00:42:57 +0000297static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
298 int *claimed);
299static ld_plugin_status all_symbols_read_hook(void);
300static ld_plugin_status cleanup_hook(void);
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000301
302extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
303ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne59349ad2014-07-03 23:28:03 +0000304 InitializeAllTargetInfos();
305 InitializeAllTargets();
306 InitializeAllTargetMCs();
307 InitializeAllAsmParsers();
308 InitializeAllAsmPrinters();
309
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000310 // We're given a pointer to the first transfer vector. We read through them
311 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
312 // contain pointers to functions that we need to call to register our own
313 // hooks. The others are addresses of functions we can use to call into gold
314 // for services.
315
316 bool registeredClaimFile = false;
Rafael Espindola0b5745a2014-06-19 21:14:13 +0000317 bool RegisteredAllSymbolsRead = false;
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000318
319 for (; tv->tv_tag != LDPT_NULL; ++tv) {
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000320 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
321 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
322 // header.
323 switch (static_cast<int>(tv->tv_tag)) {
324 case LDPT_OUTPUT_NAME:
325 output_name = tv->tv_u.tv_string;
326 break;
327 case LDPT_LINKER_OUTPUT:
328 switch (tv->tv_u.tv_val) {
329 case LDPO_REL: // .o
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000330 IsExecutable = false;
Bill Wendling0a4671b2018-07-12 20:35:58 +0000331 SplitSections = false;
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000332 break;
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000333 case LDPO_DYN: // .so
Teresa Johnson2d320e52016-08-11 14:58:12 +0000334 IsExecutable = false;
335 RelocationModel = Reloc::PIC_;
336 break;
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000337 case LDPO_PIE: // position independent executable
Teresa Johnson2d320e52016-08-11 14:58:12 +0000338 IsExecutable = true;
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000339 RelocationModel = Reloc::PIC_;
Rafael Espindolac4b55612010-06-03 21:11:20 +0000340 break;
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000341 case LDPO_EXEC: // .exe
Teresa Johnson2d320e52016-08-11 14:58:12 +0000342 IsExecutable = true;
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000343 RelocationModel = Reloc::Static;
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000344 break;
345 default:
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000346 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
347 return LDPS_ERR;
348 }
349 break;
350 case LDPT_OPTION:
351 options::process_plugin_option(tv->tv_u.tv_string);
352 break;
353 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
354 ld_plugin_register_claim_file callback;
355 callback = tv->tv_u.tv_register_claim_file;
356
357 if (callback(claim_file_hook) != LDPS_OK)
358 return LDPS_ERR;
359
360 registeredClaimFile = true;
361 } break;
362 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
363 ld_plugin_register_all_symbols_read callback;
364 callback = tv->tv_u.tv_register_all_symbols_read;
365
366 if (callback(all_symbols_read_hook) != LDPS_OK)
367 return LDPS_ERR;
368
369 RegisteredAllSymbolsRead = true;
370 } break;
371 case LDPT_REGISTER_CLEANUP_HOOK: {
372 ld_plugin_register_cleanup callback;
373 callback = tv->tv_u.tv_register_cleanup;
374
375 if (callback(cleanup_hook) != LDPS_OK)
376 return LDPS_ERR;
377 } break;
378 case LDPT_GET_INPUT_FILE:
379 get_input_file = tv->tv_u.tv_get_input_file;
380 break;
381 case LDPT_RELEASE_INPUT_FILE:
382 release_input_file = tv->tv_u.tv_release_input_file;
383 break;
384 case LDPT_ADD_SYMBOLS:
385 add_symbols = tv->tv_u.tv_add_symbols;
386 break;
387 case LDPT_GET_SYMBOLS_V2:
388 // Do not override get_symbols_v3 with get_symbols_v2.
389 if (!get_symbols)
390 get_symbols = tv->tv_u.tv_get_symbols;
391 break;
392 case LDPT_GET_SYMBOLS_V3:
393 get_symbols = tv->tv_u.tv_get_symbols;
394 break;
395 case LDPT_ADD_INPUT_FILE:
396 add_input_file = tv->tv_u.tv_add_input_file;
397 break;
398 case LDPT_SET_EXTRA_LIBRARY_PATH:
399 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
400 break;
401 case LDPT_GET_VIEW:
402 get_view = tv->tv_u.tv_get_view;
403 break;
404 case LDPT_MESSAGE:
405 message = tv->tv_u.tv_message;
406 break;
Teresa Johnsonead87652018-03-14 13:26:18 +0000407 case LDPT_GET_WRAP_SYMBOLS:
408 // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
409 // required version, this should be changed to:
410 // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
411 get_wrap_symbols =
Teresa Johnson64c4f712018-03-14 14:00:57 +0000412 (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;
Teresa Johnsonead87652018-03-14 13:26:18 +0000413 break;
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000414 default:
415 break;
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000416 }
417 }
418
Rafael Espindola98c507e2009-02-18 08:30:15 +0000419 if (!registeredClaimFile) {
Rafael Espindola601bb092014-07-30 00:38:58 +0000420 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6210a942009-02-18 17:49:06 +0000421 return LDPS_ERR;
422 }
Rafael Espindola98c507e2009-02-18 08:30:15 +0000423 if (!add_symbols) {
Rafael Espindola601bb092014-07-30 00:38:58 +0000424 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6210a942009-02-18 17:49:06 +0000425 return LDPS_ERR;
426 }
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000427
Rafael Espindola474f2232014-06-19 22:20:07 +0000428 if (!RegisteredAllSymbolsRead)
429 return LDPS_OK;
Rafael Espindola0b5745a2014-06-19 21:14:13 +0000430
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000431 if (!get_input_file) {
432 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
433 return LDPS_ERR;
Rafael Espindolaf38fdf12014-06-19 22:54:47 +0000434 }
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000435 if (!release_input_file) {
Marianne Mailhot-Sarrasind9529c52016-03-30 12:20:53 +0000436 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000437 return LDPS_ERR;
Tom Roeder9ad9c962014-06-26 20:43:27 +0000438 }
439
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000440 return LDPS_OK;
441}
442
NAKAMURA Takumifed4c6e2015-11-19 10:43:44 +0000443static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindola68016e02015-01-10 00:07:30 +0000444 std::string ErrStorage;
445 {
446 raw_string_ostream OS(ErrStorage);
447 DiagnosticPrinterRawOStream DP(OS);
448 DI.print(DP);
449 }
Rafael Espindolade833242015-03-02 19:08:03 +0000450 ld_plugin_level Level;
451 switch (DI.getSeverity()) {
452 case DS_Error:
Mandeep Singh Grangbadd06e2018-11-01 23:34:12 +0000453 Level = LDPL_FATAL;
454 break;
Rafael Espindolade833242015-03-02 19:08:03 +0000455 case DS_Warning:
456 Level = LDPL_WARNING;
457 break;
458 case DS_Note:
Rafael Espindolac90e7f72015-03-04 18:51:45 +0000459 case DS_Remark:
Rafael Espindolade833242015-03-02 19:08:03 +0000460 Level = LDPL_INFO;
461 break;
Rafael Espindolade833242015-03-02 19:08:03 +0000462 }
463 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindola68016e02015-01-10 00:07:30 +0000464}
465
Teresa Johnson2d320e52016-08-11 14:58:12 +0000466static void check(Error E, std::string Msg = "LLVM gold plugin") {
Mehdi Amini36197282016-11-11 06:04:30 +0000467 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000468 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
469 return Error::success();
470 });
NAKAMURA Takumifed4c6e2015-11-19 10:43:44 +0000471}
472
Teresa Johnson2d320e52016-08-11 14:58:12 +0000473template <typename T> static T check(Expected<T> E) {
474 if (E)
475 return std::move(*E);
476 check(E.takeError());
477 return T();
Rafael Espindolada513202015-12-10 14:19:35 +0000478}
479
Rafael Espindola04e43e62014-07-06 14:31:22 +0000480/// Called by gold to see whether this file is one that our plugin can handle.
481/// We'll try to open it and register all the symbols with add_symbol if
482/// possible.
Dan Gohmanf6920032010-04-16 00:42:57 +0000483static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
484 int *claimed) {
Rafael Espindolab5e9bf02014-08-27 20:25:55 +0000485 MemoryBufferRef BufferRef;
486 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolae5782522011-04-07 21:11:00 +0000487 if (get_view) {
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000488 const void *view;
Rafael Espindolae5782522011-04-07 21:11:00 +0000489 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola601bb092014-07-30 00:38:58 +0000490 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolae5782522011-04-07 21:11:00 +0000491 return LDPS_ERR;
492 }
Nick Lewycky39879762015-08-05 21:16:02 +0000493 BufferRef =
494 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasinccb7c902011-09-12 21:47:50 +0000495 } else {
Ivan Krasin71280b52011-09-15 23:13:00 +0000496 int64_t offset = 0;
Nick Lewyckyc1da8862009-02-05 04:14:23 +0000497 // Gold has found what might be IR part-way inside of a file, such as
498 // an .a archive.
Ivan Krasinccb7c902011-09-12 21:47:50 +0000499 if (file->offset) {
500 offset = file->offset;
501 }
Rafael Espindola7cba2a92014-07-06 17:43:13 +0000502 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
503 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
504 offset);
505 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola601bb092014-07-30 00:38:58 +0000506 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasinccb7c902011-09-12 21:47:50 +0000507 return LDPS_ERR;
508 }
Rafael Espindolab5e9bf02014-08-27 20:25:55 +0000509 Buffer = std::move(BufferOrErr.get());
510 BufferRef = Buffer->getMemBufferRef();
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000511 }
Ivan Krasinccb7c902011-09-12 21:47:50 +0000512
Rafael Espindoladf7568e2014-07-29 20:46:19 +0000513 *claimed = 1;
514
Teresa Johnson2d320e52016-08-11 14:58:12 +0000515 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
516 if (!ObjOrErr) {
517 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
518 std::error_code EC = EI.convertToErrorCode();
519 if (EC == object::object_error::invalid_file_type ||
520 EC == object::object_error::bitcode_section_not_found)
521 *claimed = 0;
522 else
Peter Collingbourne957cbf82017-03-31 04:47:07 +0000523 message(LDPL_FATAL,
Teresa Johnson2d320e52016-08-11 14:58:12 +0000524 "LLVM gold plugin has failed to create LTO module: %s",
525 EI.message().c_str());
526 });
527
528 return *claimed ? LDPS_ERR : LDPS_OK;
Ivan Krasinc170f5f2011-09-09 00:14:04 +0000529 }
Teresa Johnson2d320e52016-08-11 14:58:12 +0000530
531 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000532
Dehao Chen9c353a82017-07-10 15:31:53 +0000533 Modules.emplace_back();
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000534 claimed_file &cf = Modules.back();
Rafael Espindolacbb170d2010-08-09 21:09:46 +0000535
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000536 cf.handle = file->handle;
Teresa Johnsonbb83f892016-05-26 01:46:41 +0000537 // Keep track of the first handle for each file descriptor, since there are
538 // multiple in the case of an archive. This is used later in the case of
539 // ThinLTO parallel backends to ensure that each file is only opened and
540 // released once.
541 auto LeaderHandle =
542 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
543 cf.leader_handle = LeaderHandle->second;
544 // Save the filesize since for parallel ThinLTO backends we can only
545 // invoke get_input_file once per archive (only for the leader handle).
546 cf.filesize = file->filesize;
547 // In the case of an archive library, all but the first member must have a
548 // non-zero offset, which we can append to the file name to obtain a
549 // unique name.
550 cf.name = file->name;
551 if (file->offset)
552 cf.name += ".llvm." + std::to_string(file->offset) + "." +
Teresa Johnson2d320e52016-08-11 14:58:12 +0000553 sys::path::filename(Obj->getSourceFileName()).str();
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000554
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000555 for (auto &Sym : Obj->symbols()) {
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000556 cf.syms.push_back(ld_plugin_symbol());
557 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola3c084732014-07-29 21:46:05 +0000558 sym.version = nullptr;
Teresa Johnson2d320e52016-08-11 14:58:12 +0000559 StringRef Name = Sym.getName();
560 sym.name = strdup(Name.str().c_str());
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000561
Teresa Johnson2d320e52016-08-11 14:58:12 +0000562 ResolutionInfo &Res = ResInfo[Name];
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000563
Teresa Johnson2d320e52016-08-11 14:58:12 +0000564 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
Rafael Espindolada513202015-12-10 14:19:35 +0000565
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000566 sym.visibility = LDPV_DEFAULT;
Teresa Johnson2d320e52016-08-11 14:58:12 +0000567 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
568 if (Vis != GlobalValue::DefaultVisibility)
569 Res.DefaultVisibility = false;
570 switch (Vis) {
571 case GlobalValue::DefaultVisibility:
572 break;
573 case GlobalValue::HiddenVisibility:
574 sym.visibility = LDPV_HIDDEN;
575 break;
576 case GlobalValue::ProtectedVisibility:
577 sym.visibility = LDPV_PROTECTED;
578 break;
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000579 }
580
Peter Collingbourneaba00ee2017-03-28 22:31:35 +0000581 if (Sym.isUndefined()) {
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000582 sym.def = LDPK_UNDEF;
Peter Collingbourneaba00ee2017-03-28 22:31:35 +0000583 if (Sym.isWeak())
Rafael Espindola7431af02009-04-24 16:55:21 +0000584 sym.def = LDPK_WEAKUNDEF;
Peter Collingbourneaba00ee2017-03-28 22:31:35 +0000585 } else if (Sym.isCommon())
Teresa Johnson2d320e52016-08-11 14:58:12 +0000586 sym.def = LDPK_COMMON;
Peter Collingbourneaba00ee2017-03-28 22:31:35 +0000587 else if (Sym.isWeak())
Teresa Johnson2d320e52016-08-11 14:58:12 +0000588 sym.def = LDPK_WEAKDEF;
589 else
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000590 sym.def = LDPK_DEF;
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000591
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000592 sym.size = 0;
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000593 sym.comdat_key = nullptr;
Peter Collingbourne957cbf82017-03-31 04:47:07 +0000594 int CI = Sym.getComdatIndex();
Rafael Espindola050bf6c2016-10-25 12:02:03 +0000595 if (CI != -1) {
596 StringRef C = Obj->getComdatTable()[CI];
Rafael Espindola58121fb2016-10-17 18:51:02 +0000597 sym.comdat_key = strdup(C.str().c_str());
Rafael Espindola050bf6c2016-10-25 12:02:03 +0000598 }
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000599
600 sym.resolution = LDPR_UNKNOWN;
601 }
602
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000603 if (!cf.syms.empty()) {
Nick Lewycky39879762015-08-05 21:16:02 +0000604 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola601bb092014-07-30 00:38:58 +0000605 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000606 return LDPS_ERR;
607 }
608 }
609
Teresa Johnsonead87652018-03-14 13:26:18 +0000610 // Handle any --wrap options passed to gold, which are than passed
611 // along to the plugin.
612 if (get_wrap_symbols) {
613 const char **wrap_symbols;
614 uint64_t count = 0;
615 if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
616 message(LDPL_ERROR, "Unable to get wrap symbols!");
617 return LDPS_ERR;
618 }
619 for (uint64_t i = 0; i < count; i++) {
620 StringRef Name = wrap_symbols[i];
621 ResolutionInfo &Res = ResInfo[Name];
622 ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
623 ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
624 // Tell LTO not to inline symbols that will be overwritten.
625 Res.CanInline = false;
626 RealRes.CanInline = false;
627 // Tell LTO not to eliminate symbols that will be used after renaming.
628 Res.IsUsedInRegularObj = true;
629 WrapRes.IsUsedInRegularObj = true;
630 }
631 }
632
Nick Lewycky3e62b2d2009-02-03 07:13:24 +0000633 return LDPS_OK;
634}
635
Rafael Espindola3d1c71a2014-12-23 18:18:37 +0000636static void freeSymName(ld_plugin_symbol &Sym) {
637 free(Sym.name);
638 free(Sym.comdat_key);
639 Sym.name = nullptr;
640 Sym.comdat_key = nullptr;
641}
642
Teresa Johnson07943592016-03-04 16:36:06 +0000643/// Helper to get a file's symbols and a view into it via gold callbacks.
644static const void *getSymbolsAndView(claimed_file &F) {
Benjamin Kramerb644c0a2016-03-08 14:02:46 +0000645 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000646 if (status == LDPS_NO_SYMS)
647 return nullptr;
Teresa Johnsonb97baa52015-10-04 14:33:43 +0000648
Evgeniy Stepanovf0c747b2016-03-04 00:23:29 +0000649 if (status != LDPS_OK)
Teresa Johnsonb97baa52015-10-04 14:33:43 +0000650 message(LDPL_FATAL, "Failed to get symbol information");
651
652 const void *View;
653 if (get_view(F.handle, &View) != LDPS_OK)
654 message(LDPL_FATAL, "Failed to get a view of file");
655
Teresa Johnson07943592016-03-04 16:36:06 +0000656 return View;
657}
658
Teresa Johnson08d0e942017-03-23 19:47:39 +0000659/// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
660/// \p NewSuffix strings, if it was specified.
661static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
662 std::string &NewSuffix) {
663 assert(options::thinlto_object_suffix_replace.empty() ||
664 options::thinlto_object_suffix_replace.find(";") != StringRef::npos);
665 StringRef SuffixReplace = options::thinlto_object_suffix_replace;
Benjamin Kramere5d9cb52017-08-10 19:28:00 +0000666 std::tie(OldSuffix, NewSuffix) = SuffixReplace.split(';');
Teresa Johnson08d0e942017-03-23 19:47:39 +0000667}
668
669/// Given the original \p Path to an output file, replace any filename
670/// suffix matching \p OldSuffix with \p NewSuffix.
Benjamin Kramere5d9cb52017-08-10 19:28:00 +0000671static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
672 StringRef NewSuffix) {
Fangrui Song1f251172018-08-22 02:11:36 +0000673 if (Path.consume_back(OldSuffix))
674 return (Path + NewSuffix).str();
675 return Path;
Teresa Johnson08d0e942017-03-23 19:47:39 +0000676}
677
Teresa Johnsona63ab3c92017-07-25 19:42:32 +0000678// Returns true if S is valid as a C language identifier.
679static bool isValidCIdentifier(StringRef S) {
George Rimarc7c50af2017-10-04 11:00:30 +0000680 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
681 std::all_of(S.begin() + 1, S.end(),
682 [](char C) { return C == '_' || isAlnum(C); });
Teresa Johnsona63ab3c92017-07-25 19:42:32 +0000683}
684
Eugene Leviant72044ef2017-12-15 09:18:21 +0000685static bool isUndefined(ld_plugin_symbol &Sym) {
686 return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
687}
688
Teresa Johnson08d0e942017-03-23 19:47:39 +0000689static void addModule(LTO &Lto, claimed_file &F, const void *View,
690 StringRef Filename) {
691 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
692 Filename);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000693 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
Teresa Johnsonf1f60632015-11-21 21:55:48 +0000694
Teresa Johnson2d320e52016-08-11 14:58:12 +0000695 if (!ObjOrErr)
Peter Collingbourne394be6c2014-09-18 21:28:49 +0000696 message(LDPL_FATAL, "Could not read bitcode from file : %s",
Teresa Johnson2d320e52016-08-11 14:58:12 +0000697 toString(ObjOrErr.takeError()).c_str());
Peter Collingbourne394be6c2014-09-18 21:28:49 +0000698
Rafael Espindola4f20ed12014-12-09 16:13:59 +0000699 unsigned SymNum = 0;
Teresa Johnsona63ab3c92017-07-25 19:42:32 +0000700 std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
701 auto InputFileSyms = Input->symbols();
702 assert(InputFileSyms.size() == F.syms.size());
Teresa Johnson2d320e52016-08-11 14:58:12 +0000703 std::vector<SymbolResolution> Resols(F.syms.size());
Peter Collingbourne6f025c12016-09-14 02:55:16 +0000704 for (ld_plugin_symbol &Sym : F.syms) {
Teresa Johnsona63ab3c92017-07-25 19:42:32 +0000705 const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
Peter Collingbourne6f025c12016-09-14 02:55:16 +0000706 SymbolResolution &R = Resols[SymNum++];
Rafael Espindola4f20ed12014-12-09 16:13:59 +0000707
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000708 ld_plugin_symbol_resolution Resolution =
709 (ld_plugin_symbol_resolution)Sym.resolution;
710
Rafael Espindolada513202015-12-10 14:19:35 +0000711 ResolutionInfo &Res = ResInfo[Sym.name];
Rafael Espindola19f38682014-09-09 20:08:22 +0000712
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000713 switch (Resolution) {
714 case LDPR_UNKNOWN:
715 llvm_unreachable("Unexpected resolution");
716
717 case LDPR_RESOLVED_IR:
718 case LDPR_RESOLVED_EXEC:
719 case LDPR_RESOLVED_DYN:
Rafael Espindolada513202015-12-10 14:19:35 +0000720 case LDPR_PREEMPTED_IR:
721 case LDPR_PREEMPTED_REG:
Rafael Espindola5f928112015-01-14 13:53:50 +0000722 case LDPR_UNDEF:
Rafael Espindola5f928112015-01-14 13:53:50 +0000723 break;
724
Teresa Johnson2d320e52016-08-11 14:58:12 +0000725 case LDPR_PREVAILING_DEF_IRONLY:
Eugene Leviant72044ef2017-12-15 09:18:21 +0000726 R.Prevailing = !isUndefined(Sym);
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000727 break;
Teresa Johnson9fd97702016-08-11 12:56:40 +0000728
Teresa Johnson6f0ab852016-08-11 13:03:56 +0000729 case LDPR_PREVAILING_DEF:
Eugene Leviant72044ef2017-12-15 09:18:21 +0000730 R.Prevailing = !isUndefined(Sym);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000731 R.VisibleToRegularObj = true;
Teresa Johnson6f0ab852016-08-11 13:03:56 +0000732 break;
733
Teresa Johnson2d320e52016-08-11 14:58:12 +0000734 case LDPR_PREVAILING_DEF_IRONLY_EXP:
Eugene Leviant72044ef2017-12-15 09:18:21 +0000735 R.Prevailing = !isUndefined(Sym);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000736 if (!Res.CanOmitFromDynSym)
737 R.VisibleToRegularObj = true;
Teresa Johnson6f0ab852016-08-11 13:03:56 +0000738 break;
739 }
Teresa Johnson2d320e52016-08-11 14:58:12 +0000740
Teresa Johnsona63ab3c92017-07-25 19:42:32 +0000741 // If the symbol has a C identifier section name, we need to mark
742 // it as visible to a regular object so that LTO will keep it around
743 // to ensure the linker generates special __start_<secname> and
744 // __stop_<secname> symbols which may be used elsewhere.
745 if (isValidCIdentifier(InpSym.getSectionName()))
746 R.VisibleToRegularObj = true;
747
Teresa Johnson2d320e52016-08-11 14:58:12 +0000748 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
749 (IsExecutable || !Res.DefaultVisibility))
750 R.FinalDefinitionInLinkageUnit = true;
751
Teresa Johnsonead87652018-03-14 13:26:18 +0000752 if (!Res.CanInline)
753 R.LinkerRedefined = true;
754
755 if (Res.IsUsedInRegularObj)
756 R.VisibleToRegularObj = true;
757
Rafael Espindola3d1c71a2014-12-23 18:18:37 +0000758 freeSymName(Sym);
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000759 }
760
Teresa Johnsona63ab3c92017-07-25 19:42:32 +0000761 check(Lto.add(std::move(Input), Resols),
Teresa Johnson2d320e52016-08-11 14:58:12 +0000762 std::string("Failed to link module ") + F.name);
Rafael Espindola25016f92014-10-29 23:54:45 +0000763}
764
Benjamin Kramere5d9cb52017-08-10 19:28:00 +0000765static void recordFile(const std::string &Filename, bool TempOutFile) {
Teresa Johnson07943592016-03-04 16:36:06 +0000766 if (add_input_file(Filename.c_str()) != LDPS_OK)
767 message(LDPL_FATAL,
768 "Unable to add .o file to the link. File left behind in: %s",
769 Filename.c_str());
770 if (TempOutFile)
Benjamin Kramere5d9cb52017-08-10 19:28:00 +0000771 Cleanup.push_back(Filename);
Teresa Johnson07943592016-03-04 16:36:06 +0000772}
Rafael Espindola3fd7e372014-08-21 20:28:55 +0000773
Mehdi Aminibba5e182016-08-17 06:23:09 +0000774/// Return the desired output filename given a base input name, a flag
775/// indicating whether a temp file should be generated, and an optional task id.
776/// The new filename generated is returned in \p NewFilename.
Benjamin Kramere5d9cb52017-08-10 19:28:00 +0000777static int getOutputFileName(StringRef InFilename, bool TempOutFile,
Benjamin Kramer01823a62017-08-10 17:38:41 +0000778 SmallString<128> &NewFilename, int TaskID) {
779 int FD = -1;
Teresa Johnson07943592016-03-04 16:36:06 +0000780 if (TempOutFile) {
781 std::error_code EC =
Benjamin Kramer01823a62017-08-10 17:38:41 +0000782 sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
Teresa Johnson07943592016-03-04 16:36:06 +0000783 if (EC)
784 message(LDPL_FATAL, "Could not create temporary file: %s",
785 EC.message().c_str());
786 } else {
787 NewFilename = InFilename;
Peter Collingbourne289792d2017-01-26 02:07:05 +0000788 if (TaskID > 0)
Teresa Johnson07943592016-03-04 16:36:06 +0000789 NewFilename += utostr(TaskID);
Benjamin Kramer01823a62017-08-10 17:38:41 +0000790 std::error_code EC =
Zachary Turnerb99ddea2018-06-07 20:37:22 +0000791 sys::fs::openFileForWrite(NewFilename, FD, sys::fs::CD_CreateAlways);
Benjamin Kramer01823a62017-08-10 17:38:41 +0000792 if (EC)
793 message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
794 EC.message().c_str());
Teresa Johnson07943592016-03-04 16:36:06 +0000795 }
Benjamin Kramer01823a62017-08-10 17:38:41 +0000796 return FD;
Teresa Johnson07943592016-03-04 16:36:06 +0000797}
798
Peter Collingbourne7edf7262018-04-06 21:14:33 +0000799static CodeGenOpt::Level getCGOptLevel() {
800 switch (options::OptLevel) {
801 case 0:
802 return CodeGenOpt::None;
803 case 1:
804 return CodeGenOpt::Less;
805 case 2:
806 return CodeGenOpt::Default;
807 case 3:
808 return CodeGenOpt::Aggressive;
809 }
810 llvm_unreachable("Invalid optimization level");
811}
812
Teresa Johnsona4863812016-05-17 14:45:30 +0000813/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
814/// \p NewPrefix strings, if it was specified.
815static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
816 std::string &NewPrefix) {
817 StringRef PrefixReplace = options::thinlto_prefix_replace;
Reid Kleckner4e35fa52016-05-17 18:43:22 +0000818 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
Benjamin Kramere5d9cb52017-08-10 19:28:00 +0000819 std::tie(OldPrefix, NewPrefix) = PrefixReplace.split(';');
Teresa Johnsona4863812016-05-17 14:45:30 +0000820}
821
Vitaly Buka55523de2018-02-22 19:06:15 +0000822/// Creates instance of LTO.
823/// OnIndexWrite is callback to let caller know when LTO writes index files.
824/// LinkedObjectsFile is an output stream to write the list of object files for
825/// the final ThinLTO linking. Can be nullptr.
826static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
827 raw_fd_ostream *LinkedObjectsFile) {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000828 Config Conf;
829 ThinBackend Backend;
Teresa Johnson2d320e52016-08-11 14:58:12 +0000830
831 Conf.CPU = options::mcpu;
832 Conf.Options = InitTargetOptionsFromCodeGenFlags();
833
834 // Disable the new X86 relax relocations since gold might not support them.
835 // FIXME: Check the gold version or add a new option to enable them.
836 Conf.Options.RelaxELFRelocations = false;
837
Bill Wendling0a4671b2018-07-12 20:35:58 +0000838 // Toggle function/data sections.
Nick Desaulniers0fca1c82018-12-05 17:46:24 +0000839 if (FunctionSections.getNumOccurrences() == 0)
840 Conf.Options.FunctionSections = SplitSections;
841 if (DataSections.getNumOccurrences() == 0)
842 Conf.Options.DataSections = SplitSections;
Davide Italiano67d84652017-07-25 23:32:50 +0000843
Teresa Johnson2d320e52016-08-11 14:58:12 +0000844 Conf.MAttrs = MAttrs;
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000845 Conf.RelocModel = RelocationModel;
Bill Wendling6c008762018-06-13 05:53:59 +0000846 Conf.CodeModel = getCodeModel();
Peter Collingbourne7edf7262018-04-06 21:14:33 +0000847 Conf.CGOptLevel = getCGOptLevel();
Teresa Johnson2d320e52016-08-11 14:58:12 +0000848 Conf.DisableVerify = options::DisableVerify;
849 Conf.OptLevel = options::OptLevel;
Teresa Johnson468ae9f2016-09-23 20:35:19 +0000850 if (options::Parallelism)
851 Backend = createInProcessThinBackend(options::Parallelism);
Teresa Johnson6f0ab852016-08-11 13:03:56 +0000852 if (options::thinlto_index_only) {
Teresa Johnson6f0ab852016-08-11 13:03:56 +0000853 std::string OldPrefix, NewPrefix;
854 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
Vitaly Buka55523de2018-02-22 19:06:15 +0000855 Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
856 options::thinlto_emit_imports_files,
857 LinkedObjectsFile, OnIndexWrite);
Teresa Johnson27af2052016-05-10 13:48:23 +0000858 }
859
Teresa Johnson2d320e52016-08-11 14:58:12 +0000860 Conf.OverrideTriple = options::triple;
861 Conf.DefaultTriple = sys::getDefaultTargetTriple();
862
863 Conf.DiagHandler = diagnosticHandler;
864
Teresa Johnson2d320e52016-08-11 14:58:12 +0000865 switch (options::TheOutputType) {
866 case options::OT_NORMAL:
867 break;
868
869 case options::OT_DISABLE:
Mehdi Aminib41bec02016-08-22 16:41:58 +0000870 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
Teresa Johnson2d320e52016-08-11 14:58:12 +0000871 break;
872
873 case options::OT_BC_ONLY:
Mehdi Aminib41bec02016-08-22 16:41:58 +0000874 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000875 std::error_code EC;
876 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
877 if (EC)
878 message(LDPL_FATAL, "Failed to write the output file.");
Rafael Espindola06d62072018-02-14 19:11:32 +0000879 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000880 return false;
881 };
882 break;
883
884 case options::OT_SAVE_TEMPS:
Mehdi Aminia53e50c2016-08-18 00:12:33 +0000885 check(Conf.addSaveTemps(output_name + ".",
886 /* UseInputModulePath */ true));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000887 break;
Teresa Johnson02e82c32019-01-02 23:48:00 +0000888 case options::OT_ASM_ONLY:
889 Conf.CGFileType = TargetMachine::CGFT_AssemblyFile;
890 break;
Teresa Johnson6f0ab852016-08-11 13:03:56 +0000891 }
892
Dehao Chen7e436002016-12-16 16:48:46 +0000893 if (!options::sample_profile.empty())
894 Conf.SampleProfile = options::sample_profile;
895
Yunlian Jiangedd00e42018-04-13 05:03:28 +0000896 Conf.DwoDir = options::dwo_dir;
897
Teresa Johnson48ba6662018-04-18 13:25:23 +0000898 // Set up optimization remarks handling.
899 Conf.RemarksFilename = options::OptRemarksFilename;
900 Conf.RemarksWithHotness = options::OptRemarksWithHotness;
901
Sean Fertileabd8a852017-10-05 01:48:42 +0000902 // Use new pass manager if set in driver
903 Conf.UseNewPM = options::new_pass_manager;
Teresa Johnson65834ee2018-04-05 03:16:57 +0000904 // Debug new pass manager if requested
905 Conf.DebugPassManager = options::debug_pass_manager;
Sean Fertileabd8a852017-10-05 01:48:42 +0000906
Florian Hahna2fbfc92018-04-20 10:18:36 +0000907 Conf.StatsFile = options::stats_file;
Teresa Johnson2d320e52016-08-11 14:58:12 +0000908 return llvm::make_unique<LTO>(std::move(Conf), Backend,
Teresa Johnson468ae9f2016-09-23 20:35:19 +0000909 options::ParallelCodeGenParallelismLevel);
Teresa Johnson27af2052016-05-10 13:48:23 +0000910}
911
Teresa Johnsonb81a1e92016-09-21 19:12:05 +0000912// Write empty files that may be expected by a distributed build
913// system when invoked with thinlto_index_only. This is invoked when
914// the linker has decided not to include the given module in the
915// final link. Frequently the distributed build system will want to
916// confirm that all expected outputs are created based on all of the
917// modules provided to the linker.
Vitaly Buka2749eb22018-02-16 23:38:22 +0000918// If SkipModule is true then .thinlto.bc should contain just
919// SkipModuleByDistributedBackend flag which requests distributed backend
920// to skip the compilation of the corresponding module and produce an empty
921// object file.
Vitaly Buka23f81932018-01-30 21:19:26 +0000922static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
923 const std::string &OldPrefix,
Vitaly Buka2749eb22018-02-16 23:38:22 +0000924 const std::string &NewPrefix,
925 bool SkipModule) {
Teresa Johnsonb81a1e92016-09-21 19:12:05 +0000926 std::string NewModulePath =
927 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
928 std::error_code EC;
929 {
930 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
931 sys::fs::OpenFlags::F_None);
932 if (EC)
933 message(LDPL_FATAL, "Failed to write '%s': %s",
934 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
Vitaly Buka2749eb22018-02-16 23:38:22 +0000935
936 if (SkipModule) {
Teresa Johnsone07c2602018-06-06 22:22:01 +0000937 ModuleSummaryIndex Index(/*HaveGVs*/ false);
Vitaly Buka2749eb22018-02-16 23:38:22 +0000938 Index.setSkipModuleByDistributedBackend();
939 WriteIndexToFile(Index, OS, nullptr);
940 }
Teresa Johnsonb81a1e92016-09-21 19:12:05 +0000941 }
942 if (options::thinlto_emit_imports_files) {
943 raw_fd_ostream OS(NewModulePath + ".imports", EC,
944 sys::fs::OpenFlags::F_None);
945 if (EC)
946 message(LDPL_FATAL, "Failed to write '%s': %s",
947 (NewModulePath + ".imports").c_str(), EC.message().c_str());
948 }
949}
950
Vitaly Buka55523de2018-02-22 19:06:15 +0000951// Creates and returns output stream with a list of object files for final
952// linking of distributed ThinLTO.
953static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
954 if (options::thinlto_linked_objects_file.empty())
955 return nullptr;
956 assert(options::thinlto_index_only);
957 std::error_code EC;
958 auto LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
959 options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::F_None);
960 if (EC)
961 message(LDPL_FATAL, "Failed to create '%s': %s",
962 options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
963 return LinkedObjectsFile;
964}
965
Vitaly Bukaf662ded2018-02-22 19:06:05 +0000966/// Runs LTO and return a list of pairs <FileName, IsTemporary>.
967static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
Teresa Johnsonf4b65402016-08-20 01:24:07 +0000968 // Map to own RAII objects that manage the file opening and releasing
969 // interfaces with gold. This is needed only for ThinLTO mode, since
970 // unlike regular LTO, where addModule will result in the opened file
971 // being merged into a new combined module, we need to keep these files open
972 // through Lto->run().
973 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
974
Vitaly Buka23f81932018-01-30 21:19:26 +0000975 // Owns string objects and tells if index file was already created.
976 StringMap<bool> ObjectToIndexFileState;
977
Vitaly Buka55523de2018-02-22 19:06:15 +0000978 std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
979 std::unique_ptr<LTO> Lto = createLTO(
980 [&ObjectToIndexFileState](const std::string &Identifier) {
Vitaly Buka23f81932018-01-30 21:19:26 +0000981 ObjectToIndexFileState[Identifier] = true;
Vitaly Buka55523de2018-02-22 19:06:15 +0000982 },
983 LinkedObjects.get());
Teresa Johnsonb97baa52015-10-04 14:33:43 +0000984
Teresa Johnsonb81a1e92016-09-21 19:12:05 +0000985 std::string OldPrefix, NewPrefix;
986 if (options::thinlto_index_only)
987 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
988
Teresa Johnson08d0e942017-03-23 19:47:39 +0000989 std::string OldSuffix, NewSuffix;
990 getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
Teresa Johnson08d0e942017-03-23 19:47:39 +0000991
Rafael Espindola562fd7a2014-07-30 01:52:40 +0000992 for (claimed_file &F : Modules) {
Teresa Johnsonf4b65402016-08-20 01:24:07 +0000993 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
994 HandleToInputFile.insert(std::make_pair(
995 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
Teresa Johnson08d0e942017-03-23 19:47:39 +0000996 // In case we are thin linking with a minimized bitcode file, ensure
997 // the module paths encoded in the index reflect where the backends
998 // will locate the full bitcode files for compiling/importing.
999 std::string Identifier =
1000 getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
Vitaly Buka23f81932018-01-30 21:19:26 +00001001 auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
Teresa Johnson08d0e942017-03-23 19:47:39 +00001002 assert(ObjFilename.second);
Vitaly Buka23f81932018-01-30 21:19:26 +00001003 if (const void *View = getSymbolsAndView(F))
1004 addModule(*Lto, F, View, ObjFilename.first->first());
Vitaly Buka2749eb22018-02-16 23:38:22 +00001005 else if (options::thinlto_index_only) {
1006 ObjFilename.first->second = true;
1007 writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
1008 /* SkipModule */ true);
1009 }
Rafael Espindola38a979b2010-06-14 21:20:52 +00001010 }
Nick Lewycky3e62b2d2009-02-03 07:13:24 +00001011
Teresa Johnson2d320e52016-08-11 14:58:12 +00001012 SmallString<128> Filename;
Mehdi Aminibba5e182016-08-17 06:23:09 +00001013 // Note that getOutputFileName will append a unique ID for each task
Teresa Johnson2d320e52016-08-11 14:58:12 +00001014 if (!options::obj_path.empty())
1015 Filename = options::obj_path;
1016 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
1017 Filename = output_name + ".o";
Teresa Johnson02e82c32019-01-02 23:48:00 +00001018 else if (options::TheOutputType == options::OT_ASM_ONLY)
1019 Filename = output_name;
Teresa Johnson2d320e52016-08-11 14:58:12 +00001020 bool SaveTemps = !Filename.empty();
Rafael Espindola3fd7e372014-08-21 20:28:55 +00001021
Peter Collingbourne289792d2017-01-26 02:07:05 +00001022 size_t MaxTasks = Lto->getMaxTasks();
Vitaly Bukaf662ded2018-02-22 19:06:05 +00001023 std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
Teresa Johnson2d320e52016-08-11 14:58:12 +00001024
Peter Collingbourne91d99c62016-09-23 21:33:43 +00001025 auto AddStream =
1026 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Vitaly Bukaf662ded2018-02-22 19:06:05 +00001027 Files[Task].second = !SaveTemps;
Vitaly Buka2749eb22018-02-16 23:38:22 +00001028 int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
Vitaly Bukaf662ded2018-02-22 19:06:05 +00001029 Files[Task].first, Task);
Peter Collingbourne91d99c62016-09-23 21:33:43 +00001030 return llvm::make_unique<lto::NativeObjectStream>(
1031 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
Teresa Johnson2d320e52016-08-11 14:58:12 +00001032 };
1033
Teresa Johnson761281e2018-02-20 20:21:53 +00001034 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
Teresa Johnsonf4aea132018-02-20 19:51:30 +00001035 *AddStream(Task)->OS << MB->getBuffer();
Peter Collingbourneec179d72017-03-17 00:34:07 +00001036 };
Peter Collingbourne91d99c62016-09-23 21:33:43 +00001037
1038 NativeObjectCache Cache;
1039 if (!options::cache_dir.empty())
Peter Collingbourneec179d72017-03-17 00:34:07 +00001040 Cache = check(localCache(options::cache_dir, AddBuffer));
Peter Collingbourne91d99c62016-09-23 21:33:43 +00001041
1042 check(Lto->run(AddStream, Cache));
Teresa Johnson2d320e52016-08-11 14:58:12 +00001043
Vitaly Buka23f81932018-01-30 21:19:26 +00001044 // Write empty output files that may be expected by the distributed build
1045 // system.
1046 if (options::thinlto_index_only)
1047 for (auto &Identifier : ObjectToIndexFileState)
1048 if (!Identifier.getValue())
1049 writeEmptyDistributedBuildOutputs(Identifier.getKey(), OldPrefix,
Vitaly Buka2749eb22018-02-16 23:38:22 +00001050 NewPrefix, /* SkipModule */ false);
Vitaly Buka23f81932018-01-30 21:19:26 +00001051
Vitaly Bukaf662ded2018-02-22 19:06:05 +00001052 return Files;
1053}
1054
1055/// gold informs us that all symbols have been read. At this point, we use
1056/// get_symbols to see if any of our definitions have been overridden by a
1057/// native object file. Then, perform optimization and codegen.
1058static ld_plugin_status allSymbolsReadHook() {
1059 if (Modules.empty())
1060 return LDPS_OK;
1061
1062 if (unsigned NumOpts = options::extra.size())
1063 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
1064
1065 std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
1066
Teresa Johnson2d320e52016-08-11 14:58:12 +00001067 if (options::TheOutputType == options::OT_DISABLE ||
Teresa Johnson02e82c32019-01-02 23:48:00 +00001068 options::TheOutputType == options::OT_BC_ONLY ||
1069 options::TheOutputType == options::OT_ASM_ONLY)
Rafael Espindolaf1ca1d42014-11-24 21:18:14 +00001070 return LDPS_OK;
1071
Teresa Johnson2d320e52016-08-11 14:58:12 +00001072 if (options::thinlto_index_only) {
Teresa Johnson3e0bad62018-04-19 16:55:13 +00001073 llvm_shutdown();
Teresa Johnson2d320e52016-08-11 14:58:12 +00001074 cleanup_hook();
1075 exit(0);
Rafael Espindola62bacd62010-05-13 13:39:31 +00001076 }
Rafael Espindola648a2e62013-10-16 12:47:04 +00001077
Vitaly Bukaf662ded2018-02-22 19:06:05 +00001078 for (const auto &F : Files)
1079 if (!F.first.empty())
1080 recordFile(F.first.str(), F.second);
Nick Lewycky3e62b2d2009-02-03 07:13:24 +00001081
Rafael Espindola11f403c2010-06-23 20:20:59 +00001082 if (!options::extra_library_path.empty() &&
Rafael Espindola3fd7e372014-08-21 20:28:55 +00001083 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1084 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yangcfaa6362013-08-12 21:07:31 +00001085
Nick Lewycky3e62b2d2009-02-03 07:13:24 +00001086 return LDPS_OK;
1087}
1088
Rafael Espindolab2d2f2832014-08-11 19:06:54 +00001089static ld_plugin_status all_symbols_read_hook(void) {
Teresa Johnson2d320e52016-08-11 14:58:12 +00001090 ld_plugin_status Ret = allSymbolsReadHook();
Rafael Espindola2fbbd7a2014-11-25 20:52:49 +00001091 llvm_shutdown();
1092
Rafael Espindolaf1ca1d42014-11-24 21:18:14 +00001093 if (options::TheOutputType == options::OT_BC_ONLY ||
Teresa Johnson02e82c32019-01-02 23:48:00 +00001094 options::TheOutputType == options::OT_ASM_ONLY ||
Michael Kuperstein17a113d2015-02-12 18:21:50 +00001095 options::TheOutputType == options::OT_DISABLE) {
Davide Italiano443693f2016-03-20 20:12:33 +00001096 if (options::TheOutputType == options::OT_DISABLE) {
Michael Kuperstein17a113d2015-02-12 18:21:50 +00001097 // Remove the output file here since ld.bfd creates the output file
1098 // early.
Davide Italiano443693f2016-03-20 20:12:33 +00001099 std::error_code EC = sys::fs::remove(output_name);
1100 if (EC)
1101 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
1102 EC.message().c_str());
1103 }
Rafael Espindolab2d2f2832014-08-11 19:06:54 +00001104 exit(0);
Michael Kuperstein17a113d2015-02-12 18:21:50 +00001105 }
Rafael Espindolab2d2f2832014-08-11 19:06:54 +00001106
1107 return Ret;
1108}
1109
Dan Gohmanf6920032010-04-16 00:42:57 +00001110static ld_plugin_status cleanup_hook(void) {
Rafael Espindola562fd7a2014-07-30 01:52:40 +00001111 for (std::string &Name : Cleanup) {
1112 std::error_code EC = sys::fs::remove(Name);
Rafael Espindolab3394112013-06-17 18:38:18 +00001113 if (EC)
Rafael Espindola562fd7a2014-07-30 01:52:40 +00001114 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola601bb092014-07-30 00:38:58 +00001115 EC.message().c_str());
Rafael Espindolab3394112013-06-17 18:38:18 +00001116 }
Nick Lewycky3e62b2d2009-02-03 07:13:24 +00001117
Yi Kong74ae6062017-09-18 23:24:55 +00001118 // Prune cache
Teresa Johnson327fc512018-02-22 20:57:05 +00001119 if (!options::cache_dir.empty()) {
Yi Kong74ae6062017-09-18 23:24:55 +00001120 CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
1121 pruneCache(options::cache_dir, policy);
1122 }
1123
Nick Lewycky3e62b2d2009-02-03 07:13:24 +00001124 return LDPS_OK;
1125}