blob: 14c42671b0dfd56595eaf4d5b0b8ceb1eacaec60 [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"
34#include "llvm/Object/IRObjectFile.h"
Rafael Espindola5682ce22015-04-09 21:06:08 +000035#include "llvm/Support/raw_ostream.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"
Rafael Espindola33466a72014-08-21 20:28:55 +000041#include "llvm/Transforms/IPO.h"
42#include "llvm/Transforms/IPO/PassManagerBuilder.h"
43#include "llvm/Transforms/Utils/GlobalStatus.h"
44#include "llvm/Transforms/Utils/ModuleUtils.h"
Rafael Espindolaf7ecb112014-08-22 23:26:10 +000045#include "llvm/Transforms/Utils/ValueMapper.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000046#include <list>
Chandler Carruth07baed52014-01-13 08:04:33 +000047#include <plugin-api.h>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000048#include <system_error>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000049#include <vector>
50
Sylvestre Ledru53999792014-02-11 17:30:18 +000051#ifndef LDPO_PIE
52// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
53// Precise and Debian Wheezy (binutils 2.23 is required)
54# define LDPO_PIE 3
55#endif
56
Nick Lewyckyfb643e42009-02-03 07:13:24 +000057using namespace llvm;
58
59namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000060struct claimed_file {
61 void *handle;
62 std::vector<ld_plugin_symbol> syms;
63};
Nick Lewyckyfb643e42009-02-03 07:13:24 +000064}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000065
66static ld_plugin_status discard_message(int level, const char *format, ...) {
67 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
68 // callback in the transfer vector. This should never be called.
69 abort();
70}
71
Rafael Espindola33466a72014-08-21 20:28:55 +000072static ld_plugin_get_input_file get_input_file = nullptr;
73static ld_plugin_release_input_file release_input_file = nullptr;
Rafael Espindola176e6642014-07-29 21:46:05 +000074static ld_plugin_add_symbols add_symbols = nullptr;
75static ld_plugin_get_symbols get_symbols = nullptr;
76static ld_plugin_add_input_file add_input_file = nullptr;
77static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
78static ld_plugin_get_view get_view = nullptr;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000079static ld_plugin_message message = discard_message;
Rafael Espindola33466a72014-08-21 20:28:55 +000080static Reloc::Model RelocationModel = Reloc::Default;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000081static std::string output_name = "";
82static std::list<claimed_file> Modules;
83static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +000084static llvm::TargetOptions TargetOpts;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000085
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000086namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +000087 enum OutputType {
88 OT_NORMAL,
89 OT_DISABLE,
90 OT_BC_ONLY,
91 OT_SAVE_TEMPS
92 };
Dan Gohmanebb4ae02010-04-16 00:42:57 +000093 static bool generate_api_file = false;
Rafael Espindola6953a3a2014-11-24 21:18:14 +000094 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne070843d2015-03-19 22:01:00 +000095 static unsigned OptLevel = 2;
Peter Collingbourne87202a42015-09-01 20:40:22 +000096 static unsigned Parallelism = 1;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +000097#ifdef NDEBUG
98 static bool DisableVerify = true;
99#else
100 static bool DisableVerify = false;
101#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000102 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000103 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000104 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000105 static std::string mcpu;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000106 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000107 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000108 // as plugin exclusive to pass to the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000109 // For example, "generate-api-file" and "as"options are for the plugin
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000110 // use only and will not be passed.
Rafael Espindola125b9242014-07-29 19:17:44 +0000111 static std::vector<const char *> extra;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000112
Nick Lewycky7282dd72015-08-05 21:16:02 +0000113 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000114 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000115 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000116 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000117 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000118
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000119 if (opt == "generate-api-file") {
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000120 generate_api_file = true;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000121 } else if (opt.startswith("mcpu=")) {
122 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000123 } else if (opt.startswith("extra-library-path=")) {
124 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000125 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000126 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000127 } else if (opt.startswith("obj-path=")) {
128 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000129 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000130 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000131 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000132 TheOutputType = OT_SAVE_TEMPS;
133 } else if (opt == "disable-output") {
134 TheOutputType = OT_DISABLE;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000135 } else if (opt.size() == 2 && opt[0] == 'O') {
136 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000137 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000138 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000139 } else if (opt.startswith("jobs=")) {
140 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
141 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000142 } else if (opt == "disable-verify") {
143 DisableVerify = true;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000144 } else {
145 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000146 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
147 // add that.
148 if (extra.empty())
149 extra.push_back("LLVMgold");
150
Rafael Espindola125b9242014-07-29 19:17:44 +0000151 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000152 }
153 }
154}
155
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000156static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
157 int *claimed);
158static ld_plugin_status all_symbols_read_hook(void);
159static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000160
161extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
162ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000163 InitializeAllTargetInfos();
164 InitializeAllTargets();
165 InitializeAllTargetMCs();
166 InitializeAllAsmParsers();
167 InitializeAllAsmPrinters();
168
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000169 // We're given a pointer to the first transfer vector. We read through them
170 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
171 // contain pointers to functions that we need to call to register our own
172 // hooks. The others are addresses of functions we can use to call into gold
173 // for services.
174
175 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000176 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000177
178 for (; tv->tv_tag != LDPT_NULL; ++tv) {
179 switch (tv->tv_tag) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000180 case LDPT_OUTPUT_NAME:
181 output_name = tv->tv_u.tv_string;
182 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000183 case LDPT_LINKER_OUTPUT:
184 switch (tv->tv_u.tv_val) {
185 case LDPO_REL: // .o
186 case LDPO_DYN: // .so
Rafael Espindola76e376d2014-02-10 20:38:38 +0000187 case LDPO_PIE: // position independent executable
Rafael Espindola33466a72014-08-21 20:28:55 +0000188 RelocationModel = Reloc::PIC_;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000189 break;
190 case LDPO_EXEC: // .exe
Rafael Espindola33466a72014-08-21 20:28:55 +0000191 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000192 break;
193 default:
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000194 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000195 return LDPS_ERR;
196 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000197 break;
198 case LDPT_OPTION:
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000199 options::process_plugin_option(tv->tv_u.tv_string);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000200 break;
201 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
202 ld_plugin_register_claim_file callback;
203 callback = tv->tv_u.tv_register_claim_file;
204
Rafael Espindola54f82b72014-07-30 01:36:32 +0000205 if (callback(claim_file_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000206 return LDPS_ERR;
207
208 registeredClaimFile = true;
209 } break;
210 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
211 ld_plugin_register_all_symbols_read callback;
212 callback = tv->tv_u.tv_register_all_symbols_read;
213
Rafael Espindola54f82b72014-07-30 01:36:32 +0000214 if (callback(all_symbols_read_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000215 return LDPS_ERR;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000216
Rafael Espindola6b244b12014-06-19 21:14:13 +0000217 RegisteredAllSymbolsRead = true;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000218 } break;
219 case LDPT_REGISTER_CLEANUP_HOOK: {
220 ld_plugin_register_cleanup callback;
221 callback = tv->tv_u.tv_register_cleanup;
222
Rafael Espindola54f82b72014-07-30 01:36:32 +0000223 if (callback(cleanup_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000224 return LDPS_ERR;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000225 } break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000226 case LDPT_GET_INPUT_FILE:
227 get_input_file = tv->tv_u.tv_get_input_file;
228 break;
229 case LDPT_RELEASE_INPUT_FILE:
230 release_input_file = tv->tv_u.tv_release_input_file;
231 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000232 case LDPT_ADD_SYMBOLS:
233 add_symbols = tv->tv_u.tv_add_symbols;
234 break;
Rafael Espindolacda29112013-10-03 18:29:09 +0000235 case LDPT_GET_SYMBOLS_V2:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000236 get_symbols = tv->tv_u.tv_get_symbols;
237 break;
238 case LDPT_ADD_INPUT_FILE:
239 add_input_file = tv->tv_u.tv_add_input_file;
240 break;
Rafael Espindolaef498152010-06-23 20:20:59 +0000241 case LDPT_SET_EXTRA_LIBRARY_PATH:
242 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
243 break;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000244 case LDPT_GET_VIEW:
245 get_view = tv->tv_u.tv_get_view;
246 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000247 case LDPT_MESSAGE:
248 message = tv->tv_u.tv_message;
249 break;
250 default:
251 break;
252 }
253 }
254
Rafael Espindolae08484d2009-02-18 08:30:15 +0000255 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000256 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000257 return LDPS_ERR;
258 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000259 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000260 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000261 return LDPS_ERR;
262 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000263
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000264 if (!RegisteredAllSymbolsRead)
265 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000266
Rafael Espindola33466a72014-08-21 20:28:55 +0000267 if (!get_input_file) {
268 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
269 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000270 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000271 if (!release_input_file) {
272 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
273 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000274 }
275
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000276 return LDPS_OK;
277}
278
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000279static const GlobalObject *getBaseObject(const GlobalValue &GV) {
280 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
281 return GA->getBaseObject();
282 return cast<GlobalObject>(&GV);
283}
284
Rafael Espindola527e8462014-12-09 16:13:59 +0000285static bool shouldSkip(uint32_t Symflags) {
286 if (!(Symflags & object::BasicSymbolRef::SF_Global))
287 return true;
288 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
289 return true;
290 return false;
291}
292
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000293static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
Rafael Espindola503f8832015-03-02 19:08:03 +0000294 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
295 std::error_code EC = BDI->getError();
296 if (EC == BitcodeError::InvalidBitcodeSignature)
297 return;
298 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000299
300 std::string ErrStorage;
301 {
302 raw_string_ostream OS(ErrStorage);
303 DiagnosticPrinterRawOStream DP(OS);
304 DI.print(DP);
305 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000306 ld_plugin_level Level;
307 switch (DI.getSeverity()) {
308 case DS_Error:
309 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
310 ErrStorage.c_str());
311 llvm_unreachable("Fatal doesn't return.");
312 case DS_Warning:
313 Level = LDPL_WARNING;
314 break;
315 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000316 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000317 Level = LDPL_INFO;
318 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000319 }
320 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000321}
322
Rafael Espindolae54d8212014-07-06 14:31:22 +0000323/// Called by gold to see whether this file is one that our plugin can handle.
324/// We'll try to open it and register all the symbols with add_symbol if
325/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000326static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
327 int *claimed) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000328 LLVMContext Context;
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000329 MemoryBufferRef BufferRef;
330 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000331 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000332 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000333 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000334 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000335 return LDPS_ERR;
336 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000337 BufferRef =
338 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000339 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000340 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000341 // Gold has found what might be IR part-way inside of a file, such as
342 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000343 if (file->offset) {
344 offset = file->offset;
345 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000346 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
347 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
348 offset);
349 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000350 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000351 return LDPS_ERR;
352 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000353 Buffer = std::move(BufferOrErr.get());
354 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000355 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000356
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000357 Context.setDiagnosticHandler(diagnosticHandler);
David Blaikie10a27df2014-09-03 17:59:23 +0000358 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000359 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola33466a72014-08-21 20:28:55 +0000360 std::error_code EC = ObjOrErr.getError();
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000361 if (EC == object::object_error::invalid_file_type ||
Peter Collingbourne10039c02014-09-18 21:28:49 +0000362 EC == object::object_error::bitcode_section_not_found)
Ivan Krasin5021af52011-09-12 21:47:50 +0000363 return LDPS_OK;
364
Rafael Espindola6c472e52014-07-29 20:46:19 +0000365 *claimed = 1;
366
Rafael Espindola33466a72014-08-21 20:28:55 +0000367 if (EC) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000368 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000369 EC.message().c_str());
Rafael Espindola6c472e52014-07-29 20:46:19 +0000370 return LDPS_ERR;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000371 }
David Blaikie10a27df2014-09-03 17:59:23 +0000372 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000373
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000374 Modules.resize(Modules.size() + 1);
375 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000376
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000377 cf.handle = file->handle;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000378
Rafael Espindola33466a72014-08-21 20:28:55 +0000379 for (auto &Sym : Obj->symbols()) {
380 uint32_t Symflags = Sym.getFlags();
Rafael Espindola527e8462014-12-09 16:13:59 +0000381 if (shouldSkip(Symflags))
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000382 continue;
383
384 cf.syms.push_back(ld_plugin_symbol());
385 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000386 sym.version = nullptr;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000387
Rafael Espindola33466a72014-08-21 20:28:55 +0000388 SmallString<64> Name;
389 {
390 raw_svector_ostream OS(Name);
391 Sym.printName(OS);
392 }
393 sym.name = strdup(Name.c_str());
394
395 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
396
397 sym.visibility = LDPV_DEFAULT;
398 if (GV) {
399 switch (GV->getVisibility()) {
400 case GlobalValue::DefaultVisibility:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000401 sym.visibility = LDPV_DEFAULT;
402 break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000403 case GlobalValue::HiddenVisibility:
404 sym.visibility = LDPV_HIDDEN;
405 break;
406 case GlobalValue::ProtectedVisibility:
407 sym.visibility = LDPV_PROTECTED;
408 break;
409 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000410 }
411
Rafael Espindola33466a72014-08-21 20:28:55 +0000412 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
413 sym.def = LDPK_UNDEF;
414 if (GV && GV->hasExternalWeakLinkage())
Rafael Espindola56548522009-04-24 16:55:21 +0000415 sym.def = LDPK_WEAKUNDEF;
Rafael Espindola33466a72014-08-21 20:28:55 +0000416 } else {
417 sym.def = LDPK_DEF;
418 if (GV) {
419 assert(!GV->hasExternalWeakLinkage() &&
420 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
421 if (GV->hasCommonLinkage())
422 sym.def = LDPK_COMMON;
423 else if (GV->isWeakForLinker())
424 sym.def = LDPK_WEAKDEF;
425 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000426 }
427
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000428 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000429 sym.comdat_key = nullptr;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000430 if (GV) {
431 const GlobalObject *Base = getBaseObject(*GV);
432 if (!Base)
433 message(LDPL_FATAL, "Unable to determine comdat of alias!");
434 const Comdat *C = Base->getComdat();
435 if (C)
436 sym.comdat_key = strdup(C->getName().str().c_str());
437 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
438 sym.comdat_key = strdup(sym.name);
439 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000440
441 sym.resolution = LDPR_UNKNOWN;
442 }
443
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000444 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000445 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000446 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000447 return LDPS_ERR;
448 }
449 }
450
451 return LDPS_OK;
452}
453
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000454static void keepGlobalValue(GlobalValue &GV,
455 std::vector<GlobalAlias *> &KeptAliases) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000456 assert(!GV.hasLocalLinkage());
457
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000458 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
459 KeptAliases.push_back(GA);
460
Rafael Espindola33466a72014-08-21 20:28:55 +0000461 switch (GV.getLinkage()) {
462 default:
463 break;
464 case GlobalValue::LinkOnceAnyLinkage:
465 GV.setLinkage(GlobalValue::WeakAnyLinkage);
466 break;
467 case GlobalValue::LinkOnceODRLinkage:
468 GV.setLinkage(GlobalValue::WeakODRLinkage);
469 break;
470 }
471
472 assert(!GV.isDiscardableIfUnused());
473}
474
Rafael Espindola33466a72014-08-21 20:28:55 +0000475static void internalize(GlobalValue &GV) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000476 if (GV.isDeclarationForLinker())
Rafael Espindola33466a72014-08-21 20:28:55 +0000477 return; // We get here if there is a matching asm definition.
478 if (!GV.hasLocalLinkage())
479 GV.setLinkage(GlobalValue::InternalLinkage);
480}
481
482static void drop(GlobalValue &GV) {
483 if (auto *F = dyn_cast<Function>(&GV)) {
484 F->deleteBody();
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000485 F->setComdat(nullptr); // Should deleteBody do this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000486 return;
487 }
488
489 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
490 Var->setInitializer(nullptr);
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000491 Var->setLinkage(
492 GlobalValue::ExternalLinkage); // Should setInitializer do this?
493 Var->setComdat(nullptr); // and this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000494 return;
495 }
496
497 auto &Alias = cast<GlobalAlias>(GV);
498 Module &M = *Alias.getParent();
499 PointerType &Ty = *cast<PointerType>(Alias.getType());
500 GlobalValue::LinkageTypes L = Alias.getLinkage();
501 auto *Var =
502 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
503 /*Initializer*/ nullptr);
504 Var->takeName(&Alias);
505 Alias.replaceAllUsesWith(Var);
Rafael Espindola71143ed2014-09-10 19:39:41 +0000506 Alias.eraseFromParent();
Rafael Espindola33466a72014-08-21 20:28:55 +0000507}
508
509static const char *getResolutionName(ld_plugin_symbol_resolution R) {
510 switch (R) {
511 case LDPR_UNKNOWN:
512 return "UNKNOWN";
513 case LDPR_UNDEF:
514 return "UNDEF";
515 case LDPR_PREVAILING_DEF:
516 return "PREVAILING_DEF";
517 case LDPR_PREVAILING_DEF_IRONLY:
518 return "PREVAILING_DEF_IRONLY";
519 case LDPR_PREEMPTED_REG:
520 return "PREEMPTED_REG";
521 case LDPR_PREEMPTED_IR:
522 return "PREEMPTED_IR";
523 case LDPR_RESOLVED_IR:
524 return "RESOLVED_IR";
525 case LDPR_RESOLVED_EXEC:
526 return "RESOLVED_EXEC";
527 case LDPR_RESOLVED_DYN:
528 return "RESOLVED_DYN";
529 case LDPR_PREVAILING_DEF_IRONLY_EXP:
530 return "PREVAILING_DEF_IRONLY_EXP";
531 }
Rafael Espindola2754dbb2014-10-10 00:48:13 +0000532 llvm_unreachable("Unknown resolution");
Rafael Espindola33466a72014-08-21 20:28:55 +0000533}
534
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000535namespace {
536class LocalValueMaterializer : public ValueMaterializer {
537 DenseSet<GlobalValue *> &Dropped;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000538 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000539
540public:
541 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
542 Value *materializeValueFor(Value *V) override;
543};
544}
545
546Value *LocalValueMaterializer::materializeValueFor(Value *V) {
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000547 auto *GO = dyn_cast<GlobalObject>(V);
548 if (!GO)
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000549 return nullptr;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000550
551 auto I = LocalVersions.find(GO);
552 if (I != LocalVersions.end())
553 return I->second;
554
555 if (!Dropped.count(GO))
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000556 return nullptr;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000557
558 Module &M = *GO->getParent();
559 GlobalValue::LinkageTypes L = GO->getLinkage();
560 GlobalObject *Declaration;
561 if (auto *F = dyn_cast<Function>(GO)) {
562 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
563 } else {
564 auto *Var = cast<GlobalVariable>(GO);
565 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
566 Var->isConstant(), L,
567 /*Initializer*/ nullptr);
568 }
569 Declaration->takeName(GO);
570 Declaration->copyAttributesFrom(GO);
571
572 GO->setLinkage(GlobalValue::InternalLinkage);
573 GO->setName(Declaration->getName());
574 Dropped.erase(GO);
575 GO->replaceAllUsesWith(Declaration);
576
577 LocalVersions[Declaration] = GO;
578
579 return GO;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000580}
581
582static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
583 LocalValueMaterializer *Materializer) {
584 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
585}
586
Rafael Espindola538c9a82014-12-23 18:18:37 +0000587static void freeSymName(ld_plugin_symbol &Sym) {
588 free(Sym.name);
589 free(Sym.comdat_key);
590 Sym.name = nullptr;
591 Sym.comdat_key = nullptr;
592}
593
Rafael Espindola33466a72014-08-21 20:28:55 +0000594static std::unique_ptr<Module>
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000595getModuleForFile(LLVMContext &Context, claimed_file &F,
Rafael Espindola503f8832015-03-02 19:08:03 +0000596 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
Rafael Espindola33466a72014-08-21 20:28:55 +0000597 StringSet<> &Internalize, StringSet<> &Maybe) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000598
Nick Lewycky7282dd72015-08-05 21:16:02 +0000599 if (get_symbols(F.handle, F.syms.size(), F.syms.data()) != LDPS_OK)
Rafael Espindola33466a72014-08-21 20:28:55 +0000600 message(LDPL_FATAL, "Failed to get symbol information");
601
602 const void *View;
603 if (get_view(F.handle, &View) != LDPS_OK)
604 message(LDPL_FATAL, "Failed to get a view of file");
605
Rafael Espindola503f8832015-03-02 19:08:03 +0000606 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
607 Info.name);
Rafael Espindola527e8462014-12-09 16:13:59 +0000608 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000609 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola527e8462014-12-09 16:13:59 +0000610
611 if (std::error_code EC = ObjOrErr.getError())
Peter Collingbourne10039c02014-09-18 21:28:49 +0000612 message(LDPL_FATAL, "Could not read bitcode from file : %s",
613 EC.message().c_str());
614
Rafael Espindola527e8462014-12-09 16:13:59 +0000615 object::IRObjectFile &Obj = **ObjOrErr;
Rafael Espindola33466a72014-08-21 20:28:55 +0000616
Rafael Espindola527e8462014-12-09 16:13:59 +0000617 Module &M = Obj.getModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000618
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000619 M.materializeMetadata();
620 UpgradeDebugInfo(M);
Rafael Espindola503f8832015-03-02 19:08:03 +0000621
Rafael Espindola33466a72014-08-21 20:28:55 +0000622 SmallPtrSet<GlobalValue *, 8> Used;
Rafael Espindola527e8462014-12-09 16:13:59 +0000623 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
Rafael Espindola33466a72014-08-21 20:28:55 +0000624
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000625 DenseSet<GlobalValue *> Drop;
626 std::vector<GlobalAlias *> KeptAliases;
Rafael Espindola527e8462014-12-09 16:13:59 +0000627
628 unsigned SymNum = 0;
629 for (auto &ObjSym : Obj.symbols()) {
630 if (shouldSkip(ObjSym.getFlags()))
631 continue;
632 ld_plugin_symbol &Sym = F.syms[SymNum];
633 ++SymNum;
634
Rafael Espindola33466a72014-08-21 20:28:55 +0000635 ld_plugin_symbol_resolution Resolution =
636 (ld_plugin_symbol_resolution)Sym.resolution;
637
638 if (options::generate_api_file)
639 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
640
Rafael Espindola527e8462014-12-09 16:13:59 +0000641 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
Rafael Espindola538c9a82014-12-23 18:18:37 +0000642 if (!GV) {
643 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000644 continue; // Asm symbol.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000645 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000646
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000647 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
Rafael Espindola890db272014-09-09 20:08:22 +0000648 // Common linkage is special. There is no single symbol that wins the
649 // resolution. Instead we have to collect the maximum alignment and size.
650 // The IR linker does that for us if we just pass it every common GV.
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000651 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
652 // internalize once the IR linker has done its job.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000653 freeSymName(Sym);
Rafael Espindola890db272014-09-09 20:08:22 +0000654 continue;
655 }
656
Rafael Espindola33466a72014-08-21 20:28:55 +0000657 switch (Resolution) {
658 case LDPR_UNKNOWN:
659 llvm_unreachable("Unexpected resolution");
660
661 case LDPR_RESOLVED_IR:
662 case LDPR_RESOLVED_EXEC:
663 case LDPR_RESOLVED_DYN:
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000664 assert(GV->isDeclarationForLinker());
Rafael Espindola33466a72014-08-21 20:28:55 +0000665 break;
666
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000667 case LDPR_UNDEF:
Rafael Espindola9e3e53f2015-01-14 20:08:46 +0000668 if (!GV->isDeclarationForLinker()) {
Rafael Espindola0fd9e5f2015-01-14 19:43:32 +0000669 assert(GV->hasComdat());
670 Drop.insert(GV);
671 }
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000672 break;
673
Rafael Espindola33466a72014-08-21 20:28:55 +0000674 case LDPR_PREVAILING_DEF_IRONLY: {
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000675 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000676 if (!Used.count(GV)) {
677 // Since we use the regular lib/Linker, we cannot just internalize GV
678 // now or it will not be copied to the merged module. Instead we force
679 // it to be copied and then internalize it.
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000680 Internalize.insert(GV->getName());
Rafael Espindola33466a72014-08-21 20:28:55 +0000681 }
682 break;
683 }
684
685 case LDPR_PREVAILING_DEF:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000686 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000687 break;
688
Rafael Espindola33466a72014-08-21 20:28:55 +0000689 case LDPR_PREEMPTED_IR:
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000690 // Gold might have selected a linkonce_odr and preempted a weak_odr.
691 // In that case we have to make sure we don't end up internalizing it.
692 if (!GV->isDiscardableIfUnused())
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000693 Maybe.erase(GV->getName());
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000694
695 // fall-through
696 case LDPR_PREEMPTED_REG:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000697 Drop.insert(GV);
Rafael Espindola33466a72014-08-21 20:28:55 +0000698 break;
699
700 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
701 // We can only check for address uses after we merge the modules. The
702 // reason is that this GV might have a copy in another module
703 // and in that module the address might be significant, but that
704 // copy will be LDPR_PREEMPTED_IR.
705 if (GV->hasLinkOnceODRLinkage())
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000706 Maybe.insert(GV->getName());
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000707 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000708 break;
709 }
710 }
711
Rafael Espindola538c9a82014-12-23 18:18:37 +0000712 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000713 }
714
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000715 ValueToValueMapTy VM;
716 LocalValueMaterializer Materializer(Drop);
717 for (GlobalAlias *GA : KeptAliases) {
718 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
719 // expression is being dropped. If that is the case, that GV must be copied.
720 Constant *Aliasee = GA->getAliasee();
721 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000722 GA->setAliasee(Replacement);
Rafael Espindola33466a72014-08-21 20:28:55 +0000723 }
724
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000725 for (auto *GV : Drop)
726 drop(*GV);
727
Rafael Espindola527e8462014-12-09 16:13:59 +0000728 return Obj.takeModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000729}
730
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000731static void runLTOPasses(Module &M, TargetMachine &TM) {
Chandler Carruthdf47bb92015-07-24 17:23:09 +0000732 M.setDataLayout(TM.createDataLayout());
Rafael Espindola85d85092015-02-21 00:13:15 +0000733
Chandler Carruth30d69c22015-02-13 10:01:29 +0000734 legacy::PassManager passes;
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000735 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
736
Chandler Carruth5700b372015-02-13 21:10:58 +0000737 PassManagerBuilder PMB;
Sylvestre Ledru450f97d2015-01-24 13:59:08 +0000738 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
Rafael Espindola33466a72014-08-21 20:28:55 +0000739 PMB.Inliner = createFunctionInliningPass();
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000740 // Unconditionally verify input since it is not verified before this
741 // point and has unknown origin.
Rafael Espindola33466a72014-08-21 20:28:55 +0000742 PMB.VerifyInput = true;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000743 PMB.VerifyOutput = !options::DisableVerify;
Rafael Espindola8391dbd2014-10-30 00:11:24 +0000744 PMB.LoopVectorize = true;
Rafael Espindola919fb532014-10-30 00:38:54 +0000745 PMB.SLPVectorize = true;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000746 PMB.OptLevel = options::OptLevel;
Alexey Samsonov5ce24482015-01-30 19:14:04 +0000747 PMB.populateLTOPassManager(passes);
Rafael Espindola33466a72014-08-21 20:28:55 +0000748 passes.run(M);
749}
750
Duncan P. N. Exon Smithe406c842015-04-15 00:13:51 +0000751static void saveBCFile(StringRef Path, Module &M) {
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000752 std::error_code EC;
753 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
754 if (EC)
755 message(LDPL_FATAL, "Failed to write the output file.");
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +0000756 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000757}
758
Peter Collingbourne87202a42015-09-01 20:40:22 +0000759static void codegen(std::unique_ptr<Module> M) {
760 const std::string &TripleStr = M->getTargetTriple();
Rafael Espindola33466a72014-08-21 20:28:55 +0000761 Triple TheTriple(TripleStr);
762
763 std::string ErrMsg;
764 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
765 if (!TheTarget)
766 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
767
768 if (unsigned NumOpts = options::extra.size())
769 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
770
771 SubtargetFeatures Features;
772 Features.getDefaultSubtargetFeatures(TheTriple);
773 for (const std::string &A : MAttrs)
774 Features.AddFeature(A);
775
776 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Peter Collingbourne070843d2015-03-19 22:01:00 +0000777 CodeGenOpt::Level CGOptLevel;
778 switch (options::OptLevel) {
779 case 0:
780 CGOptLevel = CodeGenOpt::None;
781 break;
782 case 1:
783 CGOptLevel = CodeGenOpt::Less;
784 break;
785 case 2:
786 CGOptLevel = CodeGenOpt::Default;
787 break;
788 case 3:
789 CGOptLevel = CodeGenOpt::Aggressive;
790 break;
791 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000792 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
793 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
Peter Collingbourne070843d2015-03-19 22:01:00 +0000794 CodeModel::Default, CGOptLevel));
Rafael Espindola33466a72014-08-21 20:28:55 +0000795
Peter Collingbourne87202a42015-09-01 20:40:22 +0000796 runLTOPasses(*M, *TM);
Rafael Espindola33466a72014-08-21 20:28:55 +0000797
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000798 if (options::TheOutputType == options::OT_SAVE_TEMPS)
Peter Collingbourne87202a42015-09-01 20:40:22 +0000799 saveBCFile(output_name + ".opt.bc", *M);
Rafael Espindola33466a72014-08-21 20:28:55 +0000800
801 SmallString<128> Filename;
Rafael Espindola92200d22015-06-15 13:36:27 +0000802 if (!options::obj_path.empty())
803 Filename = options::obj_path;
804 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
805 Filename = output_name + ".o";
806
Peter Collingbourne87202a42015-09-01 20:40:22 +0000807 std::vector<SmallString<128>> Filenames(options::Parallelism);
Rafael Espindola92200d22015-06-15 13:36:27 +0000808 bool TempOutFile = Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000809 {
Peter Collingbourne87202a42015-09-01 20:40:22 +0000810 // Open a file descriptor for each backend thread. This is done in a block
811 // so that the output file descriptors are closed before gold opens them.
812 std::list<llvm::raw_fd_ostream> OSs;
813 std::vector<llvm::raw_pwrite_stream *> OSPtrs(options::Parallelism);
814 for (unsigned I = 0; I != options::Parallelism; ++I) {
815 int FD;
816 if (TempOutFile) {
817 std::error_code EC =
818 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filenames[I]);
819 if (EC)
820 message(LDPL_FATAL, "Could not create temporary file: %s",
821 EC.message().c_str());
822 } else {
823 Filenames[I] = Filename;
824 if (options::Parallelism != 1)
825 Filenames[I] += utostr(I);
826 std::error_code EC =
827 sys::fs::openFileForWrite(Filenames[I], FD, sys::fs::F_None);
828 if (EC)
829 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
830 }
831 OSs.emplace_back(FD, true);
832 OSPtrs[I] = &OSs.back();
833 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000834
Peter Collingbourne87202a42015-09-01 20:40:22 +0000835 // Run backend threads.
836 splitCodeGen(std::move(M), OSPtrs, options::mcpu, Features.getString(),
837 Options, RelocationModel, CodeModel::Default, CGOptLevel);
Rafael Espindola33466a72014-08-21 20:28:55 +0000838 }
839
Peter Collingbourne87202a42015-09-01 20:40:22 +0000840 for (auto &Filename : Filenames) {
841 if (add_input_file(Filename.c_str()) != LDPS_OK)
842 message(LDPL_FATAL,
843 "Unable to add .o file to the link. File left behind in: %s",
844 Filename.c_str());
845 if (TempOutFile)
846 Cleanup.push_back(Filename.c_str());
847 }
Rafael Espindola282a4702013-10-31 20:51:58 +0000848}
849
Rafael Espindolab6393292014-07-30 01:23:45 +0000850/// gold informs us that all symbols have been read. At this point, we use
851/// get_symbols to see if any of our definitions have been overridden by a
852/// native object file. Then, perform optimization and codegen.
Rafael Espindola33466a72014-08-21 20:28:55 +0000853static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
854 if (Modules.empty())
855 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000856
Rafael Espindola33466a72014-08-21 20:28:55 +0000857 LLVMContext Context;
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000858 Context.setDiagnosticHandler(diagnosticHandler, nullptr, true);
Rafael Espindola503f8832015-03-02 19:08:03 +0000859
Rafael Espindola33466a72014-08-21 20:28:55 +0000860 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
861 Linker L(Combined.get());
862
863 std::string DefaultTriple = sys::getDefaultTargetTriple();
864
865 StringSet<> Internalize;
866 StringSet<> Maybe;
Rafael Espindolad2aac572014-07-30 01:52:40 +0000867 for (claimed_file &F : Modules) {
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000868 ld_plugin_input_file File;
869 if (get_input_file(F.handle, &File) != LDPS_OK)
870 message(LDPL_FATAL, "Failed to get file information");
Rafael Espindola33466a72014-08-21 20:28:55 +0000871 std::unique_ptr<Module> M =
Rafael Espindola503f8832015-03-02 19:08:03 +0000872 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe);
Rafael Espindola33466a72014-08-21 20:28:55 +0000873 if (!options::triple.empty())
874 M->setTargetTriple(options::triple.c_str());
875 else if (M->getTargetTriple().empty()) {
876 M->setTargetTriple(DefaultTriple);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000877 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000878
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000879 if (L.linkInModule(M.get()))
880 message(LDPL_FATAL, "Failed to link module");
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000881 if (release_input_file(F.handle) != LDPS_OK)
882 message(LDPL_FATAL, "Failed to release file information");
Rafael Espindola77b6d012010-06-14 21:20:52 +0000883 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000884
Rafael Espindola33466a72014-08-21 20:28:55 +0000885 for (const auto &Name : Internalize) {
886 GlobalValue *GV = Combined->getNamedValue(Name.first());
887 if (GV)
888 internalize(*GV);
889 }
890
891 for (const auto &Name : Maybe) {
892 GlobalValue *GV = Combined->getNamedValue(Name.first());
893 if (!GV)
894 continue;
895 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
896 if (canBeOmittedFromSymbolTable(GV))
897 internalize(*GV);
898 }
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000899
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000900 if (options::TheOutputType == options::OT_DISABLE)
901 return LDPS_OK;
902
903 if (options::TheOutputType != options::OT_NORMAL) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000904 std::string path;
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000905 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000906 path = output_name;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000907 else
908 path = output_name + ".bc";
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000909 saveBCFile(path, *L.getModule());
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000910 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola55b32542014-08-11 19:06:54 +0000911 return LDPS_OK;
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000912 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000913
Peter Collingbourne87202a42015-09-01 20:40:22 +0000914 codegen(std::move(Combined));
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000915
Rafael Espindolaef498152010-06-23 20:20:59 +0000916 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000917 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
918 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000919
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000920 return LDPS_OK;
921}
922
Rafael Espindola55b32542014-08-11 19:06:54 +0000923static ld_plugin_status all_symbols_read_hook(void) {
924 ld_plugin_status Ret;
925 if (!options::generate_api_file) {
926 Ret = allSymbolsReadHook(nullptr);
927 } else {
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000928 std::error_code EC;
929 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
930 if (EC)
Rafael Espindola55b32542014-08-11 19:06:54 +0000931 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000932 EC.message().c_str());
Rafael Espindola33466a72014-08-21 20:28:55 +0000933 Ret = allSymbolsReadHook(&ApiFile);
Rafael Espindola55b32542014-08-11 19:06:54 +0000934 }
935
Rafael Espindola947bdb62014-11-25 20:52:49 +0000936 llvm_shutdown();
937
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000938 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000939 options::TheOutputType == options::OT_DISABLE) {
940 if (options::TheOutputType == options::OT_DISABLE)
941 // Remove the output file here since ld.bfd creates the output file
942 // early.
943 sys::fs::remove(output_name);
Rafael Espindola55b32542014-08-11 19:06:54 +0000944 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000945 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000946
947 return Ret;
948}
949
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000950static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000951 for (std::string &Name : Cleanup) {
952 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000953 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000954 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000955 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000956 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000957
958 return LDPS_OK;
959}