blob: 9f8b0b20f613883d3ee354379eaa6c3cb2c6ab56 [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
Dylan Noblesmith9e5b1782011-12-22 23:04:07 +000015#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
Rafael Espindolaf7ecb112014-08-22 23:26:10 +000016#include "llvm/ADT/DenseSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000017#include "llvm/ADT/StringSet.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
NAKAMURA Takumib0a52832015-02-02 05:47:30 +000019#include "llvm/Analysis/TargetTransformInfo.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000020#include "llvm/Bitcode/ReaderWriter.h"
21#include "llvm/CodeGen/Analysis.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000022#include "llvm/CodeGen/CommandFlags.h"
Peter Collingbourne87202a42015-09-01 20:40:22 +000023#include "llvm/CodeGen/ParallelCG.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000024#include "llvm/IR/AutoUpgrade.h"
Rafael Espindola890db272014-09-09 20:08:22 +000025#include "llvm/IR/Constants.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000026#include "llvm/IR/DiagnosticInfo.h"
27#include "llvm/IR/DiagnosticPrinter.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000028#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000029#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000030#include "llvm/IR/Module.h"
31#include "llvm/IR/Verifier.h"
32#include "llvm/Linker/Linker.h"
33#include "llvm/MC/SubtargetFeature.h"
Teresa Johnson403a7872015-10-04 14:33:43 +000034#include "llvm/Object/FunctionIndexObjectFile.h"
Teresa Johnsonb13dbd62015-12-09 19:45:55 +000035#include "llvm/Object/IRObjectFile.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000036#include "llvm/Support/Host.h"
Rafael Espindola947bdb62014-11-25 20:52:49 +000037#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000039#include "llvm/Support/TargetRegistry.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000040#include "llvm/Support/TargetSelect.h"
Teresa Johnsonb13dbd62015-12-09 19:45:55 +000041#include "llvm/Support/raw_ostream.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000042#include "llvm/Transforms/IPO.h"
43#include "llvm/Transforms/IPO/PassManagerBuilder.h"
44#include "llvm/Transforms/Utils/GlobalStatus.h"
45#include "llvm/Transforms/Utils/ModuleUtils.h"
Rafael Espindolaf7ecb112014-08-22 23:26:10 +000046#include "llvm/Transforms/Utils/ValueMapper.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000047#include <list>
Chandler Carruth07baed52014-01-13 08:04:33 +000048#include <plugin-api.h>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000049#include <system_error>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000050#include <vector>
51
Sylvestre Ledru53999792014-02-11 17:30:18 +000052#ifndef LDPO_PIE
53// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
54// Precise and Debian Wheezy (binutils 2.23 is required)
55# define LDPO_PIE 3
56#endif
57
Nick Lewyckyfb643e42009-02-03 07:13:24 +000058using namespace llvm;
59
60namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000061struct claimed_file {
62 void *handle;
63 std::vector<ld_plugin_symbol> syms;
64};
Nick Lewyckyfb643e42009-02-03 07:13:24 +000065}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000066
67static ld_plugin_status discard_message(int level, const char *format, ...) {
68 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
69 // callback in the transfer vector. This should never be called.
70 abort();
71}
72
Rafael Espindola33466a72014-08-21 20:28:55 +000073static ld_plugin_get_input_file get_input_file = nullptr;
74static ld_plugin_release_input_file release_input_file = nullptr;
Rafael Espindola176e6642014-07-29 21:46:05 +000075static ld_plugin_add_symbols add_symbols = nullptr;
76static ld_plugin_get_symbols get_symbols = nullptr;
77static ld_plugin_add_input_file add_input_file = nullptr;
78static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
79static ld_plugin_get_view get_view = nullptr;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000080static ld_plugin_message message = discard_message;
Rafael Espindola33466a72014-08-21 20:28:55 +000081static Reloc::Model RelocationModel = Reloc::Default;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000082static std::string output_name = "";
83static std::list<claimed_file> Modules;
84static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +000085static llvm::TargetOptions TargetOpts;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000086
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000087namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +000088 enum OutputType {
89 OT_NORMAL,
90 OT_DISABLE,
91 OT_BC_ONLY,
92 OT_SAVE_TEMPS
93 };
Dan Gohmanebb4ae02010-04-16 00:42:57 +000094 static bool generate_api_file = false;
Rafael Espindola6953a3a2014-11-24 21:18:14 +000095 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne070843d2015-03-19 22:01:00 +000096 static unsigned OptLevel = 2;
Peter Collingbourne87202a42015-09-01 20:40:22 +000097 static unsigned Parallelism = 1;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +000098#ifdef NDEBUG
99 static bool DisableVerify = true;
100#else
101 static bool DisableVerify = false;
102#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000103 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000104 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000105 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000106 static std::string mcpu;
Teresa Johnson403a7872015-10-04 14:33:43 +0000107 // When the thinlto plugin option is specified, only read the function
108 // the information from intermediate files and write a combined
109 // global index for the ThinLTO backends.
110 static bool thinlto = false;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000111 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000112 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000113 // as plugin exclusive to pass to the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000114 // For example, "generate-api-file" and "as"options are for the plugin
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000115 // use only and will not be passed.
Rafael Espindola125b9242014-07-29 19:17:44 +0000116 static std::vector<const char *> extra;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000117
Nick Lewycky7282dd72015-08-05 21:16:02 +0000118 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000119 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000120 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000121 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000122 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000123
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000124 if (opt == "generate-api-file") {
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000125 generate_api_file = true;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000126 } else if (opt.startswith("mcpu=")) {
127 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000128 } else if (opt.startswith("extra-library-path=")) {
129 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000130 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000131 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000132 } else if (opt.startswith("obj-path=")) {
133 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000134 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000135 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000136 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000137 TheOutputType = OT_SAVE_TEMPS;
138 } else if (opt == "disable-output") {
139 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000140 } else if (opt == "thinlto") {
141 thinlto = true;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000142 } else if (opt.size() == 2 && opt[0] == 'O') {
143 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000144 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000145 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000146 } else if (opt.startswith("jobs=")) {
147 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
148 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000149 } else if (opt == "disable-verify") {
150 DisableVerify = true;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000151 } else {
152 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000153 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
154 // add that.
155 if (extra.empty())
156 extra.push_back("LLVMgold");
157
Rafael Espindola125b9242014-07-29 19:17:44 +0000158 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000159 }
160 }
161}
162
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000163static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
164 int *claimed);
165static ld_plugin_status all_symbols_read_hook(void);
166static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000167
168extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
169ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000170 InitializeAllTargetInfos();
171 InitializeAllTargets();
172 InitializeAllTargetMCs();
173 InitializeAllAsmParsers();
174 InitializeAllAsmPrinters();
175
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000176 // We're given a pointer to the first transfer vector. We read through them
177 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
178 // contain pointers to functions that we need to call to register our own
179 // hooks. The others are addresses of functions we can use to call into gold
180 // for services.
181
182 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000183 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000184
185 for (; tv->tv_tag != LDPT_NULL; ++tv) {
186 switch (tv->tv_tag) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000187 case LDPT_OUTPUT_NAME:
188 output_name = tv->tv_u.tv_string;
189 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000190 case LDPT_LINKER_OUTPUT:
191 switch (tv->tv_u.tv_val) {
192 case LDPO_REL: // .o
193 case LDPO_DYN: // .so
Rafael Espindola76e376d2014-02-10 20:38:38 +0000194 case LDPO_PIE: // position independent executable
Rafael Espindola33466a72014-08-21 20:28:55 +0000195 RelocationModel = Reloc::PIC_;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000196 break;
197 case LDPO_EXEC: // .exe
Rafael Espindola33466a72014-08-21 20:28:55 +0000198 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000199 break;
200 default:
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000201 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000202 return LDPS_ERR;
203 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000204 break;
205 case LDPT_OPTION:
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000206 options::process_plugin_option(tv->tv_u.tv_string);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000207 break;
208 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
209 ld_plugin_register_claim_file callback;
210 callback = tv->tv_u.tv_register_claim_file;
211
Rafael Espindola54f82b72014-07-30 01:36:32 +0000212 if (callback(claim_file_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000213 return LDPS_ERR;
214
215 registeredClaimFile = true;
216 } break;
217 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
218 ld_plugin_register_all_symbols_read callback;
219 callback = tv->tv_u.tv_register_all_symbols_read;
220
Rafael Espindola54f82b72014-07-30 01:36:32 +0000221 if (callback(all_symbols_read_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000222 return LDPS_ERR;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000223
Rafael Espindola6b244b12014-06-19 21:14:13 +0000224 RegisteredAllSymbolsRead = true;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000225 } break;
226 case LDPT_REGISTER_CLEANUP_HOOK: {
227 ld_plugin_register_cleanup callback;
228 callback = tv->tv_u.tv_register_cleanup;
229
Rafael Espindola54f82b72014-07-30 01:36:32 +0000230 if (callback(cleanup_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000231 return LDPS_ERR;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000232 } break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000233 case LDPT_GET_INPUT_FILE:
234 get_input_file = tv->tv_u.tv_get_input_file;
235 break;
236 case LDPT_RELEASE_INPUT_FILE:
237 release_input_file = tv->tv_u.tv_release_input_file;
238 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000239 case LDPT_ADD_SYMBOLS:
240 add_symbols = tv->tv_u.tv_add_symbols;
241 break;
Rafael Espindolacda29112013-10-03 18:29:09 +0000242 case LDPT_GET_SYMBOLS_V2:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000243 get_symbols = tv->tv_u.tv_get_symbols;
244 break;
245 case LDPT_ADD_INPUT_FILE:
246 add_input_file = tv->tv_u.tv_add_input_file;
247 break;
Rafael Espindolaef498152010-06-23 20:20:59 +0000248 case LDPT_SET_EXTRA_LIBRARY_PATH:
249 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
250 break;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000251 case LDPT_GET_VIEW:
252 get_view = tv->tv_u.tv_get_view;
253 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000254 case LDPT_MESSAGE:
255 message = tv->tv_u.tv_message;
256 break;
257 default:
258 break;
259 }
260 }
261
Rafael Espindolae08484d2009-02-18 08:30:15 +0000262 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000263 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000264 return LDPS_ERR;
265 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000266 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000267 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000268 return LDPS_ERR;
269 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000270
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000271 if (!RegisteredAllSymbolsRead)
272 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000273
Rafael Espindola33466a72014-08-21 20:28:55 +0000274 if (!get_input_file) {
275 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
276 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000277 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000278 if (!release_input_file) {
279 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
280 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000281 }
282
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000283 return LDPS_OK;
284}
285
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000286static const GlobalObject *getBaseObject(const GlobalValue &GV) {
287 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
288 return GA->getBaseObject();
289 return cast<GlobalObject>(&GV);
290}
291
Rafael Espindola527e8462014-12-09 16:13:59 +0000292static bool shouldSkip(uint32_t Symflags) {
293 if (!(Symflags & object::BasicSymbolRef::SF_Global))
294 return true;
295 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
296 return true;
297 return false;
298}
299
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000300static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindola503f8832015-03-02 19:08:03 +0000301 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
302 std::error_code EC = BDI->getError();
303 if (EC == BitcodeError::InvalidBitcodeSignature)
304 return;
305 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000306
307 std::string ErrStorage;
308 {
309 raw_string_ostream OS(ErrStorage);
310 DiagnosticPrinterRawOStream DP(OS);
311 DI.print(DP);
312 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000313 ld_plugin_level Level;
314 switch (DI.getSeverity()) {
315 case DS_Error:
316 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
317 ErrStorage.c_str());
318 llvm_unreachable("Fatal doesn't return.");
319 case DS_Warning:
320 Level = LDPL_WARNING;
321 break;
322 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000323 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000324 Level = LDPL_INFO;
325 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000326 }
327 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000328}
329
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000330static void diagnosticHandlerForContext(const DiagnosticInfo &DI,
331 void *Context) {
332 diagnosticHandler(DI);
333}
334
Rafael Espindolae54d8212014-07-06 14:31:22 +0000335/// Called by gold to see whether this file is one that our plugin can handle.
336/// We'll try to open it and register all the symbols with add_symbol if
337/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000338static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
339 int *claimed) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000340 LLVMContext Context;
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000341 MemoryBufferRef BufferRef;
342 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000343 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000344 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000345 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000346 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000347 return LDPS_ERR;
348 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000349 BufferRef =
350 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000351 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000352 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000353 // Gold has found what might be IR part-way inside of a file, such as
354 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000355 if (file->offset) {
356 offset = file->offset;
357 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000358 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
359 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
360 offset);
361 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000362 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000363 return LDPS_ERR;
364 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000365 Buffer = std::move(BufferOrErr.get());
366 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000367 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000368
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000369 Context.setDiagnosticHandler(diagnosticHandlerForContext);
David Blaikie10a27df2014-09-03 17:59:23 +0000370 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000371 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola33466a72014-08-21 20:28:55 +0000372 std::error_code EC = ObjOrErr.getError();
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000373 if (EC == object::object_error::invalid_file_type ||
Peter Collingbourne10039c02014-09-18 21:28:49 +0000374 EC == object::object_error::bitcode_section_not_found)
Ivan Krasin5021af52011-09-12 21:47:50 +0000375 return LDPS_OK;
376
Rafael Espindola6c472e52014-07-29 20:46:19 +0000377 *claimed = 1;
378
Rafael Espindola33466a72014-08-21 20:28:55 +0000379 if (EC) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000380 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000381 EC.message().c_str());
Rafael Espindola6c472e52014-07-29 20:46:19 +0000382 return LDPS_ERR;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000383 }
David Blaikie10a27df2014-09-03 17:59:23 +0000384 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000385
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000386 Modules.resize(Modules.size() + 1);
387 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000388
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000389 cf.handle = file->handle;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000390
Teresa Johnson403a7872015-10-04 14:33:43 +0000391 // If we are doing ThinLTO compilation, don't need to process the symbols.
392 // Later we simply build a combined index file after all files are claimed.
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000393 if (options::thinlto)
394 return LDPS_OK;
Teresa Johnson403a7872015-10-04 14:33:43 +0000395
Rafael Espindola33466a72014-08-21 20:28:55 +0000396 for (auto &Sym : Obj->symbols()) {
397 uint32_t Symflags = Sym.getFlags();
Rafael Espindola527e8462014-12-09 16:13:59 +0000398 if (shouldSkip(Symflags))
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000399 continue;
400
401 cf.syms.push_back(ld_plugin_symbol());
402 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000403 sym.version = nullptr;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000404
Rafael Espindola33466a72014-08-21 20:28:55 +0000405 SmallString<64> Name;
406 {
407 raw_svector_ostream OS(Name);
408 Sym.printName(OS);
409 }
410 sym.name = strdup(Name.c_str());
411
412 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
413
414 sym.visibility = LDPV_DEFAULT;
415 if (GV) {
416 switch (GV->getVisibility()) {
417 case GlobalValue::DefaultVisibility:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000418 sym.visibility = LDPV_DEFAULT;
419 break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000420 case GlobalValue::HiddenVisibility:
421 sym.visibility = LDPV_HIDDEN;
422 break;
423 case GlobalValue::ProtectedVisibility:
424 sym.visibility = LDPV_PROTECTED;
425 break;
426 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000427 }
428
Rafael Espindola33466a72014-08-21 20:28:55 +0000429 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
430 sym.def = LDPK_UNDEF;
431 if (GV && GV->hasExternalWeakLinkage())
Rafael Espindola56548522009-04-24 16:55:21 +0000432 sym.def = LDPK_WEAKUNDEF;
Rafael Espindola33466a72014-08-21 20:28:55 +0000433 } else {
434 sym.def = LDPK_DEF;
435 if (GV) {
436 assert(!GV->hasExternalWeakLinkage() &&
437 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
438 if (GV->hasCommonLinkage())
439 sym.def = LDPK_COMMON;
440 else if (GV->isWeakForLinker())
441 sym.def = LDPK_WEAKDEF;
442 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000443 }
444
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000445 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000446 sym.comdat_key = nullptr;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000447 if (GV) {
448 const GlobalObject *Base = getBaseObject(*GV);
449 if (!Base)
450 message(LDPL_FATAL, "Unable to determine comdat of alias!");
451 const Comdat *C = Base->getComdat();
452 if (C)
453 sym.comdat_key = strdup(C->getName().str().c_str());
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000454 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000455
456 sym.resolution = LDPR_UNKNOWN;
457 }
458
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000459 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000460 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000461 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000462 return LDPS_ERR;
463 }
464 }
465
466 return LDPS_OK;
467}
468
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000469static void keepGlobalValue(GlobalValue &GV,
470 std::vector<GlobalAlias *> &KeptAliases) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000471 assert(!GV.hasLocalLinkage());
472
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000473 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
474 KeptAliases.push_back(GA);
475
Rafael Espindola33466a72014-08-21 20:28:55 +0000476 switch (GV.getLinkage()) {
477 default:
478 break;
479 case GlobalValue::LinkOnceAnyLinkage:
480 GV.setLinkage(GlobalValue::WeakAnyLinkage);
481 break;
482 case GlobalValue::LinkOnceODRLinkage:
483 GV.setLinkage(GlobalValue::WeakODRLinkage);
484 break;
485 }
486
487 assert(!GV.isDiscardableIfUnused());
488}
489
Rafael Espindola33466a72014-08-21 20:28:55 +0000490static void internalize(GlobalValue &GV) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000491 if (GV.isDeclarationForLinker())
Rafael Espindola33466a72014-08-21 20:28:55 +0000492 return; // We get here if there is a matching asm definition.
493 if (!GV.hasLocalLinkage())
494 GV.setLinkage(GlobalValue::InternalLinkage);
495}
496
497static void drop(GlobalValue &GV) {
498 if (auto *F = dyn_cast<Function>(&GV)) {
499 F->deleteBody();
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000500 F->setComdat(nullptr); // Should deleteBody do this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000501 return;
502 }
503
504 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
505 Var->setInitializer(nullptr);
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000506 Var->setLinkage(
507 GlobalValue::ExternalLinkage); // Should setInitializer do this?
508 Var->setComdat(nullptr); // and this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000509 return;
510 }
511
512 auto &Alias = cast<GlobalAlias>(GV);
513 Module &M = *Alias.getParent();
514 PointerType &Ty = *cast<PointerType>(Alias.getType());
515 GlobalValue::LinkageTypes L = Alias.getLinkage();
516 auto *Var =
517 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
518 /*Initializer*/ nullptr);
519 Var->takeName(&Alias);
520 Alias.replaceAllUsesWith(Var);
Rafael Espindola71143ed2014-09-10 19:39:41 +0000521 Alias.eraseFromParent();
Rafael Espindola33466a72014-08-21 20:28:55 +0000522}
523
524static const char *getResolutionName(ld_plugin_symbol_resolution R) {
525 switch (R) {
526 case LDPR_UNKNOWN:
527 return "UNKNOWN";
528 case LDPR_UNDEF:
529 return "UNDEF";
530 case LDPR_PREVAILING_DEF:
531 return "PREVAILING_DEF";
532 case LDPR_PREVAILING_DEF_IRONLY:
533 return "PREVAILING_DEF_IRONLY";
534 case LDPR_PREEMPTED_REG:
535 return "PREEMPTED_REG";
536 case LDPR_PREEMPTED_IR:
537 return "PREEMPTED_IR";
538 case LDPR_RESOLVED_IR:
539 return "RESOLVED_IR";
540 case LDPR_RESOLVED_EXEC:
541 return "RESOLVED_EXEC";
542 case LDPR_RESOLVED_DYN:
543 return "RESOLVED_DYN";
544 case LDPR_PREVAILING_DEF_IRONLY_EXP:
545 return "PREVAILING_DEF_IRONLY_EXP";
546 }
Rafael Espindola2754dbb2014-10-10 00:48:13 +0000547 llvm_unreachable("Unknown resolution");
Rafael Espindola33466a72014-08-21 20:28:55 +0000548}
549
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000550namespace {
Manuel Klimek100f40c2015-10-20 08:21:01 +0000551class LocalValueMaterializer final : public ValueMaterializer {
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000552 DenseSet<GlobalValue *> &Dropped;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000553 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000554
555public:
556 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
Rafael Espindola19b52382015-11-27 20:28:19 +0000557 Value *materializeDeclFor(Value *V) override;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000558};
559}
560
Rafael Espindola19b52382015-11-27 20:28:19 +0000561Value *LocalValueMaterializer::materializeDeclFor(Value *V) {
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000562 auto *GO = dyn_cast<GlobalObject>(V);
563 if (!GO)
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000564 return nullptr;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000565
566 auto I = LocalVersions.find(GO);
567 if (I != LocalVersions.end())
568 return I->second;
569
570 if (!Dropped.count(GO))
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000571 return nullptr;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000572
573 Module &M = *GO->getParent();
574 GlobalValue::LinkageTypes L = GO->getLinkage();
575 GlobalObject *Declaration;
576 if (auto *F = dyn_cast<Function>(GO)) {
577 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
578 } else {
579 auto *Var = cast<GlobalVariable>(GO);
580 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
581 Var->isConstant(), L,
582 /*Initializer*/ nullptr);
583 }
584 Declaration->takeName(GO);
585 Declaration->copyAttributesFrom(GO);
586
587 GO->setLinkage(GlobalValue::InternalLinkage);
588 GO->setName(Declaration->getName());
589 Dropped.erase(GO);
590 GO->replaceAllUsesWith(Declaration);
591
592 LocalVersions[Declaration] = GO;
593
594 return GO;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000595}
596
597static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
598 LocalValueMaterializer *Materializer) {
599 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
600}
601
Rafael Espindola538c9a82014-12-23 18:18:37 +0000602static void freeSymName(ld_plugin_symbol &Sym) {
603 free(Sym.name);
604 free(Sym.comdat_key);
605 Sym.name = nullptr;
606 Sym.comdat_key = nullptr;
607}
608
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000609static std::unique_ptr<FunctionInfoIndex>
Mehdi Amini0027c1d2015-11-19 15:42:34 +0000610getFunctionIndexForFile(claimed_file &F, ld_plugin_input_file &Info) {
Teresa Johnson403a7872015-10-04 14:33:43 +0000611
612 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
613 message(LDPL_FATAL, "Failed to get symbol information");
614
615 const void *View;
616 if (get_view(F.handle, &View) != LDPS_OK)
617 message(LDPL_FATAL, "Failed to get a view of file");
618
619 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
620 Info.name);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000621
622 // Don't bother trying to build an index if there is no summary information
623 // in this bitcode file.
624 if (!object::FunctionIndexObjectFile::hasFunctionSummaryInMemBuffer(
625 BufferRef, diagnosticHandler))
626 return std::unique_ptr<FunctionInfoIndex>(nullptr);
627
Teresa Johnson403a7872015-10-04 14:33:43 +0000628 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000629 object::FunctionIndexObjectFile::create(BufferRef, diagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +0000630
631 if (std::error_code EC = ObjOrErr.getError())
632 message(LDPL_FATAL, "Could not read function index bitcode from file : %s",
633 EC.message().c_str());
634
635 object::FunctionIndexObjectFile &Obj = **ObjOrErr;
636
637 return Obj.takeIndex();
638}
639
Rafael Espindola33466a72014-08-21 20:28:55 +0000640static std::unique_ptr<Module>
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000641getModuleForFile(LLVMContext &Context, claimed_file &F,
Rafael Espindola503f8832015-03-02 19:08:03 +0000642 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
Rafael Espindola33466a72014-08-21 20:28:55 +0000643 StringSet<> &Internalize, StringSet<> &Maybe) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000644
Nick Lewycky7282dd72015-08-05 21:16:02 +0000645 if (get_symbols(F.handle, F.syms.size(), F.syms.data()) != LDPS_OK)
Rafael Espindola33466a72014-08-21 20:28:55 +0000646 message(LDPL_FATAL, "Failed to get symbol information");
647
648 const void *View;
649 if (get_view(F.handle, &View) != LDPS_OK)
650 message(LDPL_FATAL, "Failed to get a view of file");
651
Rafael Espindola503f8832015-03-02 19:08:03 +0000652 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
653 Info.name);
Rafael Espindola527e8462014-12-09 16:13:59 +0000654 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000655 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola527e8462014-12-09 16:13:59 +0000656
657 if (std::error_code EC = ObjOrErr.getError())
Peter Collingbourne10039c02014-09-18 21:28:49 +0000658 message(LDPL_FATAL, "Could not read bitcode from file : %s",
659 EC.message().c_str());
660
Rafael Espindola527e8462014-12-09 16:13:59 +0000661 object::IRObjectFile &Obj = **ObjOrErr;
Rafael Espindola33466a72014-08-21 20:28:55 +0000662
Rafael Espindola527e8462014-12-09 16:13:59 +0000663 Module &M = Obj.getModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000664
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000665 M.materializeMetadata();
666 UpgradeDebugInfo(M);
Rafael Espindola503f8832015-03-02 19:08:03 +0000667
Rafael Espindola33466a72014-08-21 20:28:55 +0000668 SmallPtrSet<GlobalValue *, 8> Used;
Rafael Espindola527e8462014-12-09 16:13:59 +0000669 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
Rafael Espindola33466a72014-08-21 20:28:55 +0000670
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000671 DenseSet<GlobalValue *> Drop;
672 std::vector<GlobalAlias *> KeptAliases;
Rafael Espindola527e8462014-12-09 16:13:59 +0000673
674 unsigned SymNum = 0;
675 for (auto &ObjSym : Obj.symbols()) {
676 if (shouldSkip(ObjSym.getFlags()))
677 continue;
678 ld_plugin_symbol &Sym = F.syms[SymNum];
679 ++SymNum;
680
Rafael Espindola33466a72014-08-21 20:28:55 +0000681 ld_plugin_symbol_resolution Resolution =
682 (ld_plugin_symbol_resolution)Sym.resolution;
683
684 if (options::generate_api_file)
685 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
686
Rafael Espindola527e8462014-12-09 16:13:59 +0000687 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
Rafael Espindola538c9a82014-12-23 18:18:37 +0000688 if (!GV) {
689 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000690 continue; // Asm symbol.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000691 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000692
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000693 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
Rafael Espindola890db272014-09-09 20:08:22 +0000694 // Common linkage is special. There is no single symbol that wins the
695 // resolution. Instead we have to collect the maximum alignment and size.
696 // The IR linker does that for us if we just pass it every common GV.
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000697 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
698 // internalize once the IR linker has done its job.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000699 freeSymName(Sym);
Rafael Espindola890db272014-09-09 20:08:22 +0000700 continue;
701 }
702
Rafael Espindola33466a72014-08-21 20:28:55 +0000703 switch (Resolution) {
704 case LDPR_UNKNOWN:
705 llvm_unreachable("Unexpected resolution");
706
707 case LDPR_RESOLVED_IR:
708 case LDPR_RESOLVED_EXEC:
709 case LDPR_RESOLVED_DYN:
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000710 assert(GV->isDeclarationForLinker());
Rafael Espindola33466a72014-08-21 20:28:55 +0000711 break;
712
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000713 case LDPR_UNDEF:
Rafael Espindola9e3e53f2015-01-14 20:08:46 +0000714 if (!GV->isDeclarationForLinker()) {
Rafael Espindola0fd9e5f2015-01-14 19:43:32 +0000715 assert(GV->hasComdat());
716 Drop.insert(GV);
717 }
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000718 break;
719
Rafael Espindola33466a72014-08-21 20:28:55 +0000720 case LDPR_PREVAILING_DEF_IRONLY: {
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000721 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000722 if (!Used.count(GV)) {
723 // Since we use the regular lib/Linker, we cannot just internalize GV
724 // now or it will not be copied to the merged module. Instead we force
725 // it to be copied and then internalize it.
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000726 Internalize.insert(GV->getName());
Rafael Espindola33466a72014-08-21 20:28:55 +0000727 }
728 break;
729 }
730
731 case LDPR_PREVAILING_DEF:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000732 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000733 break;
734
Rafael Espindola33466a72014-08-21 20:28:55 +0000735 case LDPR_PREEMPTED_IR:
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000736 // Gold might have selected a linkonce_odr and preempted a weak_odr.
737 // In that case we have to make sure we don't end up internalizing it.
738 if (!GV->isDiscardableIfUnused())
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000739 Maybe.erase(GV->getName());
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000740
741 // fall-through
742 case LDPR_PREEMPTED_REG:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000743 Drop.insert(GV);
Rafael Espindola33466a72014-08-21 20:28:55 +0000744 break;
745
746 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
747 // We can only check for address uses after we merge the modules. The
748 // reason is that this GV might have a copy in another module
749 // and in that module the address might be significant, but that
750 // copy will be LDPR_PREEMPTED_IR.
751 if (GV->hasLinkOnceODRLinkage())
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000752 Maybe.insert(GV->getName());
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000753 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000754 break;
755 }
756 }
757
Rafael Espindola538c9a82014-12-23 18:18:37 +0000758 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000759 }
760
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000761 ValueToValueMapTy VM;
762 LocalValueMaterializer Materializer(Drop);
763 for (GlobalAlias *GA : KeptAliases) {
764 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
765 // expression is being dropped. If that is the case, that GV must be copied.
766 Constant *Aliasee = GA->getAliasee();
767 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000768 GA->setAliasee(Replacement);
Rafael Espindola33466a72014-08-21 20:28:55 +0000769 }
770
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000771 for (auto *GV : Drop)
772 drop(*GV);
773
Rafael Espindola527e8462014-12-09 16:13:59 +0000774 return Obj.takeModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000775}
776
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000777static void runLTOPasses(Module &M, TargetMachine &TM) {
Chandler Carruthdf47bb92015-07-24 17:23:09 +0000778 M.setDataLayout(TM.createDataLayout());
Rafael Espindola85d85092015-02-21 00:13:15 +0000779
Chandler Carruth30d69c22015-02-13 10:01:29 +0000780 legacy::PassManager passes;
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000781 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
782
Chandler Carruth5700b372015-02-13 21:10:58 +0000783 PassManagerBuilder PMB;
Sylvestre Ledru450f97d2015-01-24 13:59:08 +0000784 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
Rafael Espindola33466a72014-08-21 20:28:55 +0000785 PMB.Inliner = createFunctionInliningPass();
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000786 // Unconditionally verify input since it is not verified before this
787 // point and has unknown origin.
Rafael Espindola33466a72014-08-21 20:28:55 +0000788 PMB.VerifyInput = true;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000789 PMB.VerifyOutput = !options::DisableVerify;
Rafael Espindola8391dbd2014-10-30 00:11:24 +0000790 PMB.LoopVectorize = true;
Rafael Espindola919fb532014-10-30 00:38:54 +0000791 PMB.SLPVectorize = true;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000792 PMB.OptLevel = options::OptLevel;
Alexey Samsonov5ce24482015-01-30 19:14:04 +0000793 PMB.populateLTOPassManager(passes);
Rafael Espindola33466a72014-08-21 20:28:55 +0000794 passes.run(M);
795}
796
Duncan P. N. Exon Smithe406c842015-04-15 00:13:51 +0000797static void saveBCFile(StringRef Path, Module &M) {
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000798 std::error_code EC;
799 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
800 if (EC)
801 message(LDPL_FATAL, "Failed to write the output file.");
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +0000802 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000803}
804
Peter Collingbourne87202a42015-09-01 20:40:22 +0000805static void codegen(std::unique_ptr<Module> M) {
806 const std::string &TripleStr = M->getTargetTriple();
Rafael Espindola33466a72014-08-21 20:28:55 +0000807 Triple TheTriple(TripleStr);
808
809 std::string ErrMsg;
810 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
811 if (!TheTarget)
812 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
813
814 if (unsigned NumOpts = options::extra.size())
815 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
816
817 SubtargetFeatures Features;
818 Features.getDefaultSubtargetFeatures(TheTriple);
819 for (const std::string &A : MAttrs)
820 Features.AddFeature(A);
821
822 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Peter Collingbourne070843d2015-03-19 22:01:00 +0000823 CodeGenOpt::Level CGOptLevel;
824 switch (options::OptLevel) {
825 case 0:
826 CGOptLevel = CodeGenOpt::None;
827 break;
828 case 1:
829 CGOptLevel = CodeGenOpt::Less;
830 break;
831 case 2:
832 CGOptLevel = CodeGenOpt::Default;
833 break;
834 case 3:
835 CGOptLevel = CodeGenOpt::Aggressive;
836 break;
837 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000838 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
839 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
Peter Collingbourne070843d2015-03-19 22:01:00 +0000840 CodeModel::Default, CGOptLevel));
Rafael Espindola33466a72014-08-21 20:28:55 +0000841
Peter Collingbourne87202a42015-09-01 20:40:22 +0000842 runLTOPasses(*M, *TM);
Rafael Espindola33466a72014-08-21 20:28:55 +0000843
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000844 if (options::TheOutputType == options::OT_SAVE_TEMPS)
Peter Collingbourne87202a42015-09-01 20:40:22 +0000845 saveBCFile(output_name + ".opt.bc", *M);
Rafael Espindola33466a72014-08-21 20:28:55 +0000846
847 SmallString<128> Filename;
Rafael Espindola92200d22015-06-15 13:36:27 +0000848 if (!options::obj_path.empty())
849 Filename = options::obj_path;
850 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
851 Filename = output_name + ".o";
852
Peter Collingbourne87202a42015-09-01 20:40:22 +0000853 std::vector<SmallString<128>> Filenames(options::Parallelism);
Rafael Espindola92200d22015-06-15 13:36:27 +0000854 bool TempOutFile = Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000855 {
Peter Collingbourne87202a42015-09-01 20:40:22 +0000856 // Open a file descriptor for each backend thread. This is done in a block
857 // so that the output file descriptors are closed before gold opens them.
858 std::list<llvm::raw_fd_ostream> OSs;
859 std::vector<llvm::raw_pwrite_stream *> OSPtrs(options::Parallelism);
860 for (unsigned I = 0; I != options::Parallelism; ++I) {
861 int FD;
862 if (TempOutFile) {
863 std::error_code EC =
864 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filenames[I]);
865 if (EC)
866 message(LDPL_FATAL, "Could not create temporary file: %s",
867 EC.message().c_str());
868 } else {
869 Filenames[I] = Filename;
870 if (options::Parallelism != 1)
871 Filenames[I] += utostr(I);
872 std::error_code EC =
873 sys::fs::openFileForWrite(Filenames[I], FD, sys::fs::F_None);
874 if (EC)
875 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
876 }
877 OSs.emplace_back(FD, true);
878 OSPtrs[I] = &OSs.back();
879 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000880
Peter Collingbourne87202a42015-09-01 20:40:22 +0000881 // Run backend threads.
882 splitCodeGen(std::move(M), OSPtrs, options::mcpu, Features.getString(),
883 Options, RelocationModel, CodeModel::Default, CGOptLevel);
Rafael Espindola33466a72014-08-21 20:28:55 +0000884 }
885
Peter Collingbourne87202a42015-09-01 20:40:22 +0000886 for (auto &Filename : Filenames) {
887 if (add_input_file(Filename.c_str()) != LDPS_OK)
888 message(LDPL_FATAL,
889 "Unable to add .o file to the link. File left behind in: %s",
890 Filename.c_str());
891 if (TempOutFile)
892 Cleanup.push_back(Filename.c_str());
893 }
Rafael Espindola282a4702013-10-31 20:51:58 +0000894}
895
Rafael Espindolab6393292014-07-30 01:23:45 +0000896/// gold informs us that all symbols have been read. At this point, we use
897/// get_symbols to see if any of our definitions have been overridden by a
898/// native object file. Then, perform optimization and codegen.
Rafael Espindola33466a72014-08-21 20:28:55 +0000899static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
900 if (Modules.empty())
901 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000902
Teresa Johnson403a7872015-10-04 14:33:43 +0000903 // If we are doing ThinLTO compilation, simply build the combined
904 // function index/summary and emit it. We don't need to parse the modules
905 // and link them in this case.
906 if (options::thinlto) {
Teresa Johnson8af8d4e2015-10-19 15:23:03 +0000907 FunctionInfoIndex CombinedIndex;
Teresa Johnson403a7872015-10-04 14:33:43 +0000908 uint64_t NextModuleId = 0;
909 for (claimed_file &F : Modules) {
910 ld_plugin_input_file File;
911 if (get_input_file(F.handle, &File) != LDPS_OK)
912 message(LDPL_FATAL, "Failed to get file information");
913
914 std::unique_ptr<FunctionInfoIndex> Index =
Mehdi Amini0027c1d2015-11-19 15:42:34 +0000915 getFunctionIndexForFile(F, File);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000916
917 // Skip files without a function summary.
918 if (!Index)
919 continue;
920
Teresa Johnson8af8d4e2015-10-19 15:23:03 +0000921 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
Teresa Johnsondb513572015-12-09 21:11:42 +0000922
923 if (release_input_file(F.handle) != LDPS_OK)
924 message(LDPL_FATAL, "Failed to release file information");
Teresa Johnson403a7872015-10-04 14:33:43 +0000925 }
926
927 std::error_code EC;
928 raw_fd_ostream OS(output_name + ".thinlto.bc", EC,
929 sys::fs::OpenFlags::F_None);
930 if (EC)
931 message(LDPL_FATAL, "Unable to open %s.thinlto.bc for writing: %s",
932 output_name.data(), EC.message().c_str());
Teresa Johnson3da931f2015-10-19 19:06:06 +0000933 WriteFunctionSummaryToFile(CombinedIndex, OS);
Teresa Johnson403a7872015-10-04 14:33:43 +0000934 OS.close();
935
936 cleanup_hook();
937 exit(0);
938 }
939
Teresa Johnsonaf9e9312015-12-09 19:49:40 +0000940 LLVMContext Context;
941 Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
942
Rafael Espindola33466a72014-08-21 20:28:55 +0000943 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
Rafael Espindolaf49a38f2015-12-04 22:08:53 +0000944 Linker L(*Combined, diagnosticHandler);
Rafael Espindola33466a72014-08-21 20:28:55 +0000945
946 std::string DefaultTriple = sys::getDefaultTargetTriple();
947
948 StringSet<> Internalize;
949 StringSet<> Maybe;
Rafael Espindolad2aac572014-07-30 01:52:40 +0000950 for (claimed_file &F : Modules) {
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000951 ld_plugin_input_file File;
952 if (get_input_file(F.handle, &File) != LDPS_OK)
953 message(LDPL_FATAL, "Failed to get file information");
Rafael Espindola33466a72014-08-21 20:28:55 +0000954 std::unique_ptr<Module> M =
Rafael Espindola503f8832015-03-02 19:08:03 +0000955 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe);
Rafael Espindola33466a72014-08-21 20:28:55 +0000956 if (!options::triple.empty())
957 M->setTargetTriple(options::triple.c_str());
958 else if (M->getTargetTriple().empty()) {
959 M->setTargetTriple(DefaultTriple);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000960 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000961
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000962 if (L.linkInModule(*M))
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000963 message(LDPL_FATAL, "Failed to link module");
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000964 if (release_input_file(F.handle) != LDPS_OK)
965 message(LDPL_FATAL, "Failed to release file information");
Rafael Espindola77b6d012010-06-14 21:20:52 +0000966 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000967
Rafael Espindola33466a72014-08-21 20:28:55 +0000968 for (const auto &Name : Internalize) {
969 GlobalValue *GV = Combined->getNamedValue(Name.first());
970 if (GV)
971 internalize(*GV);
972 }
973
974 for (const auto &Name : Maybe) {
975 GlobalValue *GV = Combined->getNamedValue(Name.first());
976 if (!GV)
977 continue;
978 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
979 if (canBeOmittedFromSymbolTable(GV))
980 internalize(*GV);
981 }
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000982
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000983 if (options::TheOutputType == options::OT_DISABLE)
984 return LDPS_OK;
985
986 if (options::TheOutputType != options::OT_NORMAL) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000987 std::string path;
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000988 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000989 path = output_name;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000990 else
991 path = output_name + ".bc";
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000992 saveBCFile(path, *Combined);
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000993 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola55b32542014-08-11 19:06:54 +0000994 return LDPS_OK;
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000995 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000996
Peter Collingbourne87202a42015-09-01 20:40:22 +0000997 codegen(std::move(Combined));
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000998
Rafael Espindolaef498152010-06-23 20:20:59 +0000999 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +00001000 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1001 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +00001002
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001003 return LDPS_OK;
1004}
1005
Rafael Espindola55b32542014-08-11 19:06:54 +00001006static ld_plugin_status all_symbols_read_hook(void) {
1007 ld_plugin_status Ret;
1008 if (!options::generate_api_file) {
1009 Ret = allSymbolsReadHook(nullptr);
1010 } else {
Rafael Espindola3fd1e992014-08-25 18:16:47 +00001011 std::error_code EC;
1012 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
1013 if (EC)
Rafael Espindola55b32542014-08-11 19:06:54 +00001014 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
Rafael Espindola3fd1e992014-08-25 18:16:47 +00001015 EC.message().c_str());
Rafael Espindola33466a72014-08-21 20:28:55 +00001016 Ret = allSymbolsReadHook(&ApiFile);
Rafael Espindola55b32542014-08-11 19:06:54 +00001017 }
1018
Rafael Espindola947bdb62014-11-25 20:52:49 +00001019 llvm_shutdown();
1020
Rafael Espindola6953a3a2014-11-24 21:18:14 +00001021 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +00001022 options::TheOutputType == options::OT_DISABLE) {
1023 if (options::TheOutputType == options::OT_DISABLE)
1024 // Remove the output file here since ld.bfd creates the output file
1025 // early.
1026 sys::fs::remove(output_name);
Rafael Espindola55b32542014-08-11 19:06:54 +00001027 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +00001028 }
Rafael Espindola55b32542014-08-11 19:06:54 +00001029
1030 return Ret;
1031}
1032
Dan Gohmanebb4ae02010-04-16 00:42:57 +00001033static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +00001034 for (std::string &Name : Cleanup) {
1035 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +00001036 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +00001037 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +00001038 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +00001039 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001040
1041 return LDPS_OK;
1042}