blob: d73e94922666cd8372f9bd6c1ce2b899e7f6944c [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"
Rafael Espindolacaabe222015-12-10 14:19:35 +000032#include "llvm/Linker/IRMover.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000033#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};
Rafael Espindolacaabe222015-12-10 14:19:35 +000065
66struct ResolutionInfo {
67 bool IsLinkonceOdr = true;
68 bool UnnamedAddr = true;
69 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
70 bool CommonInternal = false;
71 bool UseCommon = false;
72 unsigned CommonSize = 0;
73 unsigned CommonAlign = 0;
74 claimed_file *CommonFile = nullptr;
75};
Nick Lewyckyfb643e42009-02-03 07:13:24 +000076}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000077
78static ld_plugin_status discard_message(int level, const char *format, ...) {
79 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
80 // callback in the transfer vector. This should never be called.
81 abort();
82}
83
Rafael Espindola33466a72014-08-21 20:28:55 +000084static ld_plugin_get_input_file get_input_file = nullptr;
85static ld_plugin_release_input_file release_input_file = nullptr;
Rafael Espindola176e6642014-07-29 21:46:05 +000086static ld_plugin_add_symbols add_symbols = nullptr;
87static ld_plugin_get_symbols get_symbols = nullptr;
88static ld_plugin_add_input_file add_input_file = nullptr;
89static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
90static ld_plugin_get_view get_view = nullptr;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000091static ld_plugin_message message = discard_message;
Rafael Espindola33466a72014-08-21 20:28:55 +000092static Reloc::Model RelocationModel = Reloc::Default;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000093static std::string output_name = "";
94static std::list<claimed_file> Modules;
Rafael Espindolacaabe222015-12-10 14:19:35 +000095static StringMap<ResolutionInfo> ResInfo;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000096static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +000097static llvm::TargetOptions TargetOpts;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000098
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000099namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000100 enum OutputType {
101 OT_NORMAL,
102 OT_DISABLE,
103 OT_BC_ONLY,
104 OT_SAVE_TEMPS
105 };
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000106 static bool generate_api_file = false;
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000107 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000108 static unsigned OptLevel = 2;
Peter Collingbourne87202a42015-09-01 20:40:22 +0000109 static unsigned Parallelism = 1;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000110#ifdef NDEBUG
111 static bool DisableVerify = true;
112#else
113 static bool DisableVerify = false;
114#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000115 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000116 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000117 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000118 static std::string mcpu;
Teresa Johnson403a7872015-10-04 14:33:43 +0000119 // When the thinlto plugin option is specified, only read the function
120 // the information from intermediate files and write a combined
121 // global index for the ThinLTO backends.
122 static bool thinlto = false;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000123 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000124 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000125 // as plugin exclusive to pass to the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000126 // For example, "generate-api-file" and "as"options are for the plugin
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000127 // use only and will not be passed.
Rafael Espindola125b9242014-07-29 19:17:44 +0000128 static std::vector<const char *> extra;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000129
Nick Lewycky7282dd72015-08-05 21:16:02 +0000130 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000131 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000132 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000133 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000134 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000135
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000136 if (opt == "generate-api-file") {
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000137 generate_api_file = true;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000138 } else if (opt.startswith("mcpu=")) {
139 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000140 } else if (opt.startswith("extra-library-path=")) {
141 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000142 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000143 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000144 } else if (opt.startswith("obj-path=")) {
145 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000146 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000147 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000148 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000149 TheOutputType = OT_SAVE_TEMPS;
150 } else if (opt == "disable-output") {
151 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000152 } else if (opt == "thinlto") {
153 thinlto = true;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000154 } else if (opt.size() == 2 && opt[0] == 'O') {
155 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000156 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000157 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000158 } else if (opt.startswith("jobs=")) {
159 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
160 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000161 } else if (opt == "disable-verify") {
162 DisableVerify = true;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000163 } else {
164 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000165 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
166 // add that.
167 if (extra.empty())
168 extra.push_back("LLVMgold");
169
Rafael Espindola125b9242014-07-29 19:17:44 +0000170 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000171 }
172 }
173}
174
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000175static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
176 int *claimed);
177static ld_plugin_status all_symbols_read_hook(void);
178static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000179
180extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
181ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000182 InitializeAllTargetInfos();
183 InitializeAllTargets();
184 InitializeAllTargetMCs();
185 InitializeAllAsmParsers();
186 InitializeAllAsmPrinters();
187
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000188 // We're given a pointer to the first transfer vector. We read through them
189 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
190 // contain pointers to functions that we need to call to register our own
191 // hooks. The others are addresses of functions we can use to call into gold
192 // for services.
193
194 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000195 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000196
197 for (; tv->tv_tag != LDPT_NULL; ++tv) {
198 switch (tv->tv_tag) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000199 case LDPT_OUTPUT_NAME:
200 output_name = tv->tv_u.tv_string;
201 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000202 case LDPT_LINKER_OUTPUT:
203 switch (tv->tv_u.tv_val) {
204 case LDPO_REL: // .o
205 case LDPO_DYN: // .so
Rafael Espindola76e376d2014-02-10 20:38:38 +0000206 case LDPO_PIE: // position independent executable
Rafael Espindola33466a72014-08-21 20:28:55 +0000207 RelocationModel = Reloc::PIC_;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000208 break;
209 case LDPO_EXEC: // .exe
Rafael Espindola33466a72014-08-21 20:28:55 +0000210 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000211 break;
212 default:
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000213 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000214 return LDPS_ERR;
215 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000216 break;
217 case LDPT_OPTION:
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000218 options::process_plugin_option(tv->tv_u.tv_string);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000219 break;
220 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
221 ld_plugin_register_claim_file callback;
222 callback = tv->tv_u.tv_register_claim_file;
223
Rafael Espindola54f82b72014-07-30 01:36:32 +0000224 if (callback(claim_file_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000225 return LDPS_ERR;
226
227 registeredClaimFile = true;
228 } break;
229 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
230 ld_plugin_register_all_symbols_read callback;
231 callback = tv->tv_u.tv_register_all_symbols_read;
232
Rafael Espindola54f82b72014-07-30 01:36:32 +0000233 if (callback(all_symbols_read_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000234 return LDPS_ERR;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000235
Rafael Espindola6b244b12014-06-19 21:14:13 +0000236 RegisteredAllSymbolsRead = true;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000237 } break;
238 case LDPT_REGISTER_CLEANUP_HOOK: {
239 ld_plugin_register_cleanup callback;
240 callback = tv->tv_u.tv_register_cleanup;
241
Rafael Espindola54f82b72014-07-30 01:36:32 +0000242 if (callback(cleanup_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000243 return LDPS_ERR;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000244 } break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000245 case LDPT_GET_INPUT_FILE:
246 get_input_file = tv->tv_u.tv_get_input_file;
247 break;
248 case LDPT_RELEASE_INPUT_FILE:
249 release_input_file = tv->tv_u.tv_release_input_file;
250 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000251 case LDPT_ADD_SYMBOLS:
252 add_symbols = tv->tv_u.tv_add_symbols;
253 break;
Rafael Espindolacda29112013-10-03 18:29:09 +0000254 case LDPT_GET_SYMBOLS_V2:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000255 get_symbols = tv->tv_u.tv_get_symbols;
256 break;
257 case LDPT_ADD_INPUT_FILE:
258 add_input_file = tv->tv_u.tv_add_input_file;
259 break;
Rafael Espindolaef498152010-06-23 20:20:59 +0000260 case LDPT_SET_EXTRA_LIBRARY_PATH:
261 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
262 break;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000263 case LDPT_GET_VIEW:
264 get_view = tv->tv_u.tv_get_view;
265 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000266 case LDPT_MESSAGE:
267 message = tv->tv_u.tv_message;
268 break;
269 default:
270 break;
271 }
272 }
273
Rafael Espindolae08484d2009-02-18 08:30:15 +0000274 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000275 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000276 return LDPS_ERR;
277 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000278 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000279 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000280 return LDPS_ERR;
281 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000282
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000283 if (!RegisteredAllSymbolsRead)
284 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000285
Rafael Espindola33466a72014-08-21 20:28:55 +0000286 if (!get_input_file) {
287 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
288 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000289 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000290 if (!release_input_file) {
291 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
292 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000293 }
294
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000295 return LDPS_OK;
296}
297
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000298static const GlobalObject *getBaseObject(const GlobalValue &GV) {
299 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
300 return GA->getBaseObject();
301 return cast<GlobalObject>(&GV);
302}
303
Rafael Espindola527e8462014-12-09 16:13:59 +0000304static bool shouldSkip(uint32_t Symflags) {
305 if (!(Symflags & object::BasicSymbolRef::SF_Global))
306 return true;
307 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
308 return true;
309 return false;
310}
311
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000312static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindola503f8832015-03-02 19:08:03 +0000313 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
314 std::error_code EC = BDI->getError();
315 if (EC == BitcodeError::InvalidBitcodeSignature)
316 return;
317 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000318
319 std::string ErrStorage;
320 {
321 raw_string_ostream OS(ErrStorage);
322 DiagnosticPrinterRawOStream DP(OS);
323 DI.print(DP);
324 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000325 ld_plugin_level Level;
326 switch (DI.getSeverity()) {
327 case DS_Error:
328 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
329 ErrStorage.c_str());
330 llvm_unreachable("Fatal doesn't return.");
331 case DS_Warning:
332 Level = LDPL_WARNING;
333 break;
334 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000335 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000336 Level = LDPL_INFO;
337 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000338 }
339 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000340}
341
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000342static void diagnosticHandlerForContext(const DiagnosticInfo &DI,
343 void *Context) {
344 diagnosticHandler(DI);
345}
346
Rafael Espindolacaabe222015-12-10 14:19:35 +0000347static GlobalValue::VisibilityTypes
348getMinVisibility(GlobalValue::VisibilityTypes A,
349 GlobalValue::VisibilityTypes B) {
350 if (A == GlobalValue::HiddenVisibility)
351 return A;
352 if (B == GlobalValue::HiddenVisibility)
353 return B;
354 if (A == GlobalValue::ProtectedVisibility)
355 return A;
356 return B;
357}
358
Rafael Espindolae54d8212014-07-06 14:31:22 +0000359/// Called by gold to see whether this file is one that our plugin can handle.
360/// We'll try to open it and register all the symbols with add_symbol if
361/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000362static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
363 int *claimed) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000364 LLVMContext Context;
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000365 MemoryBufferRef BufferRef;
366 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000367 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000368 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000369 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000370 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000371 return LDPS_ERR;
372 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000373 BufferRef =
374 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000375 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000376 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000377 // Gold has found what might be IR part-way inside of a file, such as
378 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000379 if (file->offset) {
380 offset = file->offset;
381 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000382 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
383 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
384 offset);
385 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000386 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000387 return LDPS_ERR;
388 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000389 Buffer = std::move(BufferOrErr.get());
390 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000391 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000392
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000393 Context.setDiagnosticHandler(diagnosticHandlerForContext);
David Blaikie10a27df2014-09-03 17:59:23 +0000394 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000395 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola33466a72014-08-21 20:28:55 +0000396 std::error_code EC = ObjOrErr.getError();
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000397 if (EC == object::object_error::invalid_file_type ||
Peter Collingbourne10039c02014-09-18 21:28:49 +0000398 EC == object::object_error::bitcode_section_not_found)
Ivan Krasin5021af52011-09-12 21:47:50 +0000399 return LDPS_OK;
400
Rafael Espindola6c472e52014-07-29 20:46:19 +0000401 *claimed = 1;
402
Rafael Espindola33466a72014-08-21 20:28:55 +0000403 if (EC) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000404 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000405 EC.message().c_str());
Rafael Espindola6c472e52014-07-29 20:46:19 +0000406 return LDPS_ERR;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000407 }
David Blaikie10a27df2014-09-03 17:59:23 +0000408 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000409
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000410 Modules.resize(Modules.size() + 1);
411 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000412
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000413 cf.handle = file->handle;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000414
Teresa Johnson403a7872015-10-04 14:33:43 +0000415 // If we are doing ThinLTO compilation, don't need to process the symbols.
416 // Later we simply build a combined index file after all files are claimed.
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000417 if (options::thinlto)
418 return LDPS_OK;
Teresa Johnson403a7872015-10-04 14:33:43 +0000419
Rafael Espindola33466a72014-08-21 20:28:55 +0000420 for (auto &Sym : Obj->symbols()) {
421 uint32_t Symflags = Sym.getFlags();
Rafael Espindola527e8462014-12-09 16:13:59 +0000422 if (shouldSkip(Symflags))
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000423 continue;
424
425 cf.syms.push_back(ld_plugin_symbol());
426 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000427 sym.version = nullptr;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000428
Rafael Espindola33466a72014-08-21 20:28:55 +0000429 SmallString<64> Name;
430 {
431 raw_svector_ostream OS(Name);
432 Sym.printName(OS);
433 }
434 sym.name = strdup(Name.c_str());
435
436 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
437
Rafael Espindolacaabe222015-12-10 14:19:35 +0000438 ResolutionInfo &Res = ResInfo[sym.name];
439
Rafael Espindola33466a72014-08-21 20:28:55 +0000440 sym.visibility = LDPV_DEFAULT;
441 if (GV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000442 Res.UnnamedAddr &= GV->hasUnnamedAddr();
443 Res.IsLinkonceOdr &= GV->hasLinkOnceLinkage();
444 if (GV->hasCommonLinkage()) {
445 Res.CommonAlign = std::max(Res.CommonAlign, GV->getAlignment());
446 const DataLayout &DL = GV->getParent()->getDataLayout();
447 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
448 if (Size >= Res.CommonSize) {
449 Res.CommonSize = Size;
450 Res.CommonFile = &cf;
451 }
452 }
453 Res.Visibility = getMinVisibility(Res.Visibility, GV->getVisibility());
Rafael Espindola33466a72014-08-21 20:28:55 +0000454 switch (GV->getVisibility()) {
455 case GlobalValue::DefaultVisibility:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000456 sym.visibility = LDPV_DEFAULT;
457 break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000458 case GlobalValue::HiddenVisibility:
459 sym.visibility = LDPV_HIDDEN;
460 break;
461 case GlobalValue::ProtectedVisibility:
462 sym.visibility = LDPV_PROTECTED;
463 break;
464 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000465 }
466
Rafael Espindola33466a72014-08-21 20:28:55 +0000467 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
468 sym.def = LDPK_UNDEF;
469 if (GV && GV->hasExternalWeakLinkage())
Rafael Espindola56548522009-04-24 16:55:21 +0000470 sym.def = LDPK_WEAKUNDEF;
Rafael Espindola33466a72014-08-21 20:28:55 +0000471 } else {
472 sym.def = LDPK_DEF;
473 if (GV) {
474 assert(!GV->hasExternalWeakLinkage() &&
475 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
476 if (GV->hasCommonLinkage())
477 sym.def = LDPK_COMMON;
478 else if (GV->isWeakForLinker())
479 sym.def = LDPK_WEAKDEF;
480 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000481 }
482
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000483 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000484 sym.comdat_key = nullptr;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000485 if (GV) {
486 const GlobalObject *Base = getBaseObject(*GV);
487 if (!Base)
488 message(LDPL_FATAL, "Unable to determine comdat of alias!");
489 const Comdat *C = Base->getComdat();
490 if (C)
491 sym.comdat_key = strdup(C->getName().str().c_str());
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000492 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000493
494 sym.resolution = LDPR_UNKNOWN;
495 }
496
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000497 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000498 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000499 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000500 return LDPS_ERR;
501 }
502 }
503
504 return LDPS_OK;
505}
506
Rafael Espindola33466a72014-08-21 20:28:55 +0000507static void internalize(GlobalValue &GV) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000508 if (GV.isDeclarationForLinker())
Rafael Espindola33466a72014-08-21 20:28:55 +0000509 return; // We get here if there is a matching asm definition.
510 if (!GV.hasLocalLinkage())
511 GV.setLinkage(GlobalValue::InternalLinkage);
512}
513
Rafael Espindola33466a72014-08-21 20:28:55 +0000514static const char *getResolutionName(ld_plugin_symbol_resolution R) {
515 switch (R) {
516 case LDPR_UNKNOWN:
517 return "UNKNOWN";
518 case LDPR_UNDEF:
519 return "UNDEF";
520 case LDPR_PREVAILING_DEF:
521 return "PREVAILING_DEF";
522 case LDPR_PREVAILING_DEF_IRONLY:
523 return "PREVAILING_DEF_IRONLY";
524 case LDPR_PREEMPTED_REG:
525 return "PREEMPTED_REG";
526 case LDPR_PREEMPTED_IR:
527 return "PREEMPTED_IR";
528 case LDPR_RESOLVED_IR:
529 return "RESOLVED_IR";
530 case LDPR_RESOLVED_EXEC:
531 return "RESOLVED_EXEC";
532 case LDPR_RESOLVED_DYN:
533 return "RESOLVED_DYN";
534 case LDPR_PREVAILING_DEF_IRONLY_EXP:
535 return "PREVAILING_DEF_IRONLY_EXP";
536 }
Rafael Espindola2754dbb2014-10-10 00:48:13 +0000537 llvm_unreachable("Unknown resolution");
Rafael Espindola33466a72014-08-21 20:28:55 +0000538}
539
Rafael Espindola538c9a82014-12-23 18:18:37 +0000540static void freeSymName(ld_plugin_symbol &Sym) {
541 free(Sym.name);
542 free(Sym.comdat_key);
543 Sym.name = nullptr;
544 Sym.comdat_key = nullptr;
545}
546
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000547static std::unique_ptr<FunctionInfoIndex>
Mehdi Amini0027c1d2015-11-19 15:42:34 +0000548getFunctionIndexForFile(claimed_file &F, ld_plugin_input_file &Info) {
Teresa Johnson403a7872015-10-04 14:33:43 +0000549
550 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
551 message(LDPL_FATAL, "Failed to get symbol information");
552
553 const void *View;
554 if (get_view(F.handle, &View) != LDPS_OK)
555 message(LDPL_FATAL, "Failed to get a view of file");
556
557 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
558 Info.name);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000559
560 // Don't bother trying to build an index if there is no summary information
561 // in this bitcode file.
562 if (!object::FunctionIndexObjectFile::hasFunctionSummaryInMemBuffer(
563 BufferRef, diagnosticHandler))
564 return std::unique_ptr<FunctionInfoIndex>(nullptr);
565
Teresa Johnson403a7872015-10-04 14:33:43 +0000566 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000567 object::FunctionIndexObjectFile::create(BufferRef, diagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +0000568
569 if (std::error_code EC = ObjOrErr.getError())
570 message(LDPL_FATAL, "Could not read function index bitcode from file : %s",
571 EC.message().c_str());
572
573 object::FunctionIndexObjectFile &Obj = **ObjOrErr;
574
575 return Obj.takeIndex();
576}
577
Rafael Espindola33466a72014-08-21 20:28:55 +0000578static std::unique_ptr<Module>
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000579getModuleForFile(LLVMContext &Context, claimed_file &F,
Rafael Espindola503f8832015-03-02 19:08:03 +0000580 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
Rafael Espindolacaabe222015-12-10 14:19:35 +0000581 StringSet<> &Internalize, StringSet<> &Maybe,
582 std::vector<GlobalValue *> &Keep) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000583
Nick Lewycky7282dd72015-08-05 21:16:02 +0000584 if (get_symbols(F.handle, F.syms.size(), F.syms.data()) != LDPS_OK)
Rafael Espindola33466a72014-08-21 20:28:55 +0000585 message(LDPL_FATAL, "Failed to get symbol information");
586
587 const void *View;
588 if (get_view(F.handle, &View) != LDPS_OK)
589 message(LDPL_FATAL, "Failed to get a view of file");
590
Rafael Espindola503f8832015-03-02 19:08:03 +0000591 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
592 Info.name);
Rafael Espindola527e8462014-12-09 16:13:59 +0000593 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000594 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola527e8462014-12-09 16:13:59 +0000595
596 if (std::error_code EC = ObjOrErr.getError())
Peter Collingbourne10039c02014-09-18 21:28:49 +0000597 message(LDPL_FATAL, "Could not read bitcode from file : %s",
598 EC.message().c_str());
599
Rafael Espindola527e8462014-12-09 16:13:59 +0000600 object::IRObjectFile &Obj = **ObjOrErr;
Rafael Espindola33466a72014-08-21 20:28:55 +0000601
Rafael Espindola527e8462014-12-09 16:13:59 +0000602 Module &M = Obj.getModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000603
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000604 M.materializeMetadata();
605 UpgradeDebugInfo(M);
Rafael Espindola503f8832015-03-02 19:08:03 +0000606
Rafael Espindola33466a72014-08-21 20:28:55 +0000607 SmallPtrSet<GlobalValue *, 8> Used;
Rafael Espindola527e8462014-12-09 16:13:59 +0000608 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
Rafael Espindola33466a72014-08-21 20:28:55 +0000609
Rafael Espindola527e8462014-12-09 16:13:59 +0000610 unsigned SymNum = 0;
611 for (auto &ObjSym : Obj.symbols()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000612 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
613 if (GV && GV->hasAppendingLinkage())
614 Keep.push_back(GV);
615
Rafael Espindola527e8462014-12-09 16:13:59 +0000616 if (shouldSkip(ObjSym.getFlags()))
617 continue;
618 ld_plugin_symbol &Sym = F.syms[SymNum];
619 ++SymNum;
620
Rafael Espindola33466a72014-08-21 20:28:55 +0000621 ld_plugin_symbol_resolution Resolution =
622 (ld_plugin_symbol_resolution)Sym.resolution;
623
624 if (options::generate_api_file)
625 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
626
Rafael Espindola538c9a82014-12-23 18:18:37 +0000627 if (!GV) {
628 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000629 continue; // Asm symbol.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000630 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000631
Rafael Espindolacaabe222015-12-10 14:19:35 +0000632 ResolutionInfo &Res = ResInfo[Sym.name];
633 if (Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP && !Res.IsLinkonceOdr)
634 Resolution = LDPR_PREVAILING_DEF;
635
636 GV->setUnnamedAddr(Res.UnnamedAddr);
637 GV->setVisibility(Res.Visibility);
638
639 // Override gold's resolution for common symbols. We want the largest
640 // one to win.
641 if (GV->hasCommonLinkage()) {
642 cast<GlobalVariable>(GV)->setAlignment(Res.CommonAlign);
643 if (Resolution == LDPR_PREVAILING_DEF_IRONLY)
644 Res.CommonInternal = true;
645
646 if (Resolution == LDPR_PREVAILING_DEF_IRONLY ||
647 Resolution == LDPR_PREVAILING_DEF)
648 Res.UseCommon = true;
649
650 if (Res.CommonFile == &F && Res.UseCommon) {
651 if (Res.CommonInternal)
652 Resolution = LDPR_PREVAILING_DEF_IRONLY;
653 else
654 Resolution = LDPR_PREVAILING_DEF;
655 } else {
656 Resolution = LDPR_PREEMPTED_IR;
657 }
Rafael Espindola890db272014-09-09 20:08:22 +0000658 }
659
Rafael Espindola33466a72014-08-21 20:28:55 +0000660 switch (Resolution) {
661 case LDPR_UNKNOWN:
662 llvm_unreachable("Unexpected resolution");
663
664 case LDPR_RESOLVED_IR:
665 case LDPR_RESOLVED_EXEC:
666 case LDPR_RESOLVED_DYN:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000667 case LDPR_PREEMPTED_IR:
668 case LDPR_PREEMPTED_REG:
Rafael Espindola33466a72014-08-21 20:28:55 +0000669 break;
670
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000671 case LDPR_UNDEF:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000672 if (!GV->isDeclarationForLinker())
Rafael Espindola0fd9e5f2015-01-14 19:43:32 +0000673 assert(GV->hasComdat());
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000674 break;
675
Rafael Espindola33466a72014-08-21 20:28:55 +0000676 case LDPR_PREVAILING_DEF_IRONLY: {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000677 Keep.push_back(GV);
678 // The IR linker has to be able to map this value to a declaration,
679 // so we can only internalize after linking.
680 if (!Used.count(GV))
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000681 Internalize.insert(GV->getName());
Rafael Espindola33466a72014-08-21 20:28:55 +0000682 break;
683 }
684
685 case LDPR_PREVAILING_DEF:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000686 Keep.push_back(GV);
687 // There is a non IR use, so we have to force optimizations to keep this.
688 switch (GV->getLinkage()) {
689 default:
690 break;
691 case GlobalValue::LinkOnceAnyLinkage:
692 GV->setLinkage(GlobalValue::WeakAnyLinkage);
693 break;
694 case GlobalValue::LinkOnceODRLinkage:
695 GV->setLinkage(GlobalValue::WeakODRLinkage);
696 break;
697 }
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.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000705 Maybe.insert(GV->getName());
706 Keep.push_back(GV);
Rafael Espindola33466a72014-08-21 20:28:55 +0000707 break;
708 }
709 }
710
Rafael Espindola538c9a82014-12-23 18:18:37 +0000711 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000712 }
713
Rafael Espindola527e8462014-12-09 16:13:59 +0000714 return Obj.takeModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000715}
716
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000717static void runLTOPasses(Module &M, TargetMachine &TM) {
Chandler Carruthdf47bb92015-07-24 17:23:09 +0000718 M.setDataLayout(TM.createDataLayout());
Rafael Espindola85d85092015-02-21 00:13:15 +0000719
Chandler Carruth30d69c22015-02-13 10:01:29 +0000720 legacy::PassManager passes;
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000721 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
722
Chandler Carruth5700b372015-02-13 21:10:58 +0000723 PassManagerBuilder PMB;
Sylvestre Ledru450f97d2015-01-24 13:59:08 +0000724 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
Rafael Espindola33466a72014-08-21 20:28:55 +0000725 PMB.Inliner = createFunctionInliningPass();
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000726 // Unconditionally verify input since it is not verified before this
727 // point and has unknown origin.
Rafael Espindola33466a72014-08-21 20:28:55 +0000728 PMB.VerifyInput = true;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000729 PMB.VerifyOutput = !options::DisableVerify;
Rafael Espindola8391dbd2014-10-30 00:11:24 +0000730 PMB.LoopVectorize = true;
Rafael Espindola919fb532014-10-30 00:38:54 +0000731 PMB.SLPVectorize = true;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000732 PMB.OptLevel = options::OptLevel;
Alexey Samsonov5ce24482015-01-30 19:14:04 +0000733 PMB.populateLTOPassManager(passes);
Rafael Espindola33466a72014-08-21 20:28:55 +0000734 passes.run(M);
735}
736
Duncan P. N. Exon Smithe406c842015-04-15 00:13:51 +0000737static void saveBCFile(StringRef Path, Module &M) {
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000738 std::error_code EC;
739 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
740 if (EC)
741 message(LDPL_FATAL, "Failed to write the output file.");
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +0000742 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000743}
744
Peter Collingbourne87202a42015-09-01 20:40:22 +0000745static void codegen(std::unique_ptr<Module> M) {
746 const std::string &TripleStr = M->getTargetTriple();
Rafael Espindola33466a72014-08-21 20:28:55 +0000747 Triple TheTriple(TripleStr);
748
749 std::string ErrMsg;
750 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
751 if (!TheTarget)
752 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
753
754 if (unsigned NumOpts = options::extra.size())
755 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
756
757 SubtargetFeatures Features;
758 Features.getDefaultSubtargetFeatures(TheTriple);
759 for (const std::string &A : MAttrs)
760 Features.AddFeature(A);
761
762 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Peter Collingbourne070843d2015-03-19 22:01:00 +0000763 CodeGenOpt::Level CGOptLevel;
764 switch (options::OptLevel) {
765 case 0:
766 CGOptLevel = CodeGenOpt::None;
767 break;
768 case 1:
769 CGOptLevel = CodeGenOpt::Less;
770 break;
771 case 2:
772 CGOptLevel = CodeGenOpt::Default;
773 break;
774 case 3:
775 CGOptLevel = CodeGenOpt::Aggressive;
776 break;
777 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000778 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
779 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
Peter Collingbourne070843d2015-03-19 22:01:00 +0000780 CodeModel::Default, CGOptLevel));
Rafael Espindola33466a72014-08-21 20:28:55 +0000781
Peter Collingbourne87202a42015-09-01 20:40:22 +0000782 runLTOPasses(*M, *TM);
Rafael Espindola33466a72014-08-21 20:28:55 +0000783
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000784 if (options::TheOutputType == options::OT_SAVE_TEMPS)
Peter Collingbourne87202a42015-09-01 20:40:22 +0000785 saveBCFile(output_name + ".opt.bc", *M);
Rafael Espindola33466a72014-08-21 20:28:55 +0000786
787 SmallString<128> Filename;
Rafael Espindola92200d22015-06-15 13:36:27 +0000788 if (!options::obj_path.empty())
789 Filename = options::obj_path;
790 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
791 Filename = output_name + ".o";
792
Peter Collingbourne87202a42015-09-01 20:40:22 +0000793 std::vector<SmallString<128>> Filenames(options::Parallelism);
Rafael Espindola92200d22015-06-15 13:36:27 +0000794 bool TempOutFile = Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000795 {
Peter Collingbourne87202a42015-09-01 20:40:22 +0000796 // Open a file descriptor for each backend thread. This is done in a block
797 // so that the output file descriptors are closed before gold opens them.
798 std::list<llvm::raw_fd_ostream> OSs;
799 std::vector<llvm::raw_pwrite_stream *> OSPtrs(options::Parallelism);
800 for (unsigned I = 0; I != options::Parallelism; ++I) {
801 int FD;
802 if (TempOutFile) {
803 std::error_code EC =
804 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filenames[I]);
805 if (EC)
806 message(LDPL_FATAL, "Could not create temporary file: %s",
807 EC.message().c_str());
808 } else {
809 Filenames[I] = Filename;
810 if (options::Parallelism != 1)
811 Filenames[I] += utostr(I);
812 std::error_code EC =
813 sys::fs::openFileForWrite(Filenames[I], FD, sys::fs::F_None);
814 if (EC)
815 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
816 }
817 OSs.emplace_back(FD, true);
818 OSPtrs[I] = &OSs.back();
819 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000820
Peter Collingbourne87202a42015-09-01 20:40:22 +0000821 // Run backend threads.
822 splitCodeGen(std::move(M), OSPtrs, options::mcpu, Features.getString(),
823 Options, RelocationModel, CodeModel::Default, CGOptLevel);
Rafael Espindola33466a72014-08-21 20:28:55 +0000824 }
825
Peter Collingbourne87202a42015-09-01 20:40:22 +0000826 for (auto &Filename : Filenames) {
827 if (add_input_file(Filename.c_str()) != LDPS_OK)
828 message(LDPL_FATAL,
829 "Unable to add .o file to the link. File left behind in: %s",
830 Filename.c_str());
831 if (TempOutFile)
832 Cleanup.push_back(Filename.c_str());
833 }
Rafael Espindola282a4702013-10-31 20:51:58 +0000834}
835
Rafael Espindolab6393292014-07-30 01:23:45 +0000836/// gold informs us that all symbols have been read. At this point, we use
837/// get_symbols to see if any of our definitions have been overridden by a
838/// native object file. Then, perform optimization and codegen.
Rafael Espindola33466a72014-08-21 20:28:55 +0000839static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
840 if (Modules.empty())
841 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000842
Teresa Johnson403a7872015-10-04 14:33:43 +0000843 // If we are doing ThinLTO compilation, simply build the combined
844 // function index/summary and emit it. We don't need to parse the modules
845 // and link them in this case.
846 if (options::thinlto) {
Teresa Johnson8af8d4e2015-10-19 15:23:03 +0000847 FunctionInfoIndex CombinedIndex;
Teresa Johnson403a7872015-10-04 14:33:43 +0000848 uint64_t NextModuleId = 0;
849 for (claimed_file &F : Modules) {
850 ld_plugin_input_file File;
851 if (get_input_file(F.handle, &File) != LDPS_OK)
852 message(LDPL_FATAL, "Failed to get file information");
853
854 std::unique_ptr<FunctionInfoIndex> Index =
Mehdi Amini0027c1d2015-11-19 15:42:34 +0000855 getFunctionIndexForFile(F, File);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000856
857 // Skip files without a function summary.
858 if (!Index)
859 continue;
860
Teresa Johnson8af8d4e2015-10-19 15:23:03 +0000861 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
Teresa Johnsondb513572015-12-09 21:11:42 +0000862
863 if (release_input_file(F.handle) != LDPS_OK)
864 message(LDPL_FATAL, "Failed to release file information");
Teresa Johnson403a7872015-10-04 14:33:43 +0000865 }
866
867 std::error_code EC;
868 raw_fd_ostream OS(output_name + ".thinlto.bc", EC,
869 sys::fs::OpenFlags::F_None);
870 if (EC)
871 message(LDPL_FATAL, "Unable to open %s.thinlto.bc for writing: %s",
872 output_name.data(), EC.message().c_str());
Teresa Johnson3da931f2015-10-19 19:06:06 +0000873 WriteFunctionSummaryToFile(CombinedIndex, OS);
Teresa Johnson403a7872015-10-04 14:33:43 +0000874 OS.close();
875
876 cleanup_hook();
877 exit(0);
878 }
879
Teresa Johnsonaf9e9312015-12-09 19:49:40 +0000880 LLVMContext Context;
881 Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
882
Rafael Espindola33466a72014-08-21 20:28:55 +0000883 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000884 IRMover L(*Combined, diagnosticHandler);
Rafael Espindola33466a72014-08-21 20:28:55 +0000885
886 std::string DefaultTriple = sys::getDefaultTargetTriple();
887
888 StringSet<> Internalize;
889 StringSet<> Maybe;
Rafael Espindolad2aac572014-07-30 01:52:40 +0000890 for (claimed_file &F : Modules) {
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000891 ld_plugin_input_file File;
892 if (get_input_file(F.handle, &File) != LDPS_OK)
893 message(LDPL_FATAL, "Failed to get file information");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000894 std::vector<GlobalValue *> Keep;
Rafael Espindola33466a72014-08-21 20:28:55 +0000895 std::unique_ptr<Module> M =
Rafael Espindolacaabe222015-12-10 14:19:35 +0000896 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe, Keep);
Rafael Espindola33466a72014-08-21 20:28:55 +0000897 if (!options::triple.empty())
898 M->setTargetTriple(options::triple.c_str());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000899 else if (M->getTargetTriple().empty())
Rafael Espindola33466a72014-08-21 20:28:55 +0000900 M->setTargetTriple(DefaultTriple);
Rafael Espindola33466a72014-08-21 20:28:55 +0000901
Rafael Espindolacaabe222015-12-10 14:19:35 +0000902 if (L.move(*M, Keep, [](GlobalValue &, IRMover::ValueAdder) {}))
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000903 message(LDPL_FATAL, "Failed to link module");
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000904 if (release_input_file(F.handle) != LDPS_OK)
905 message(LDPL_FATAL, "Failed to release file information");
Rafael Espindola77b6d012010-06-14 21:20:52 +0000906 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000907
Rafael Espindola33466a72014-08-21 20:28:55 +0000908 for (const auto &Name : Internalize) {
909 GlobalValue *GV = Combined->getNamedValue(Name.first());
910 if (GV)
911 internalize(*GV);
912 }
913
914 for (const auto &Name : Maybe) {
915 GlobalValue *GV = Combined->getNamedValue(Name.first());
916 if (!GV)
917 continue;
918 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
919 if (canBeOmittedFromSymbolTable(GV))
920 internalize(*GV);
921 }
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000922
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000923 if (options::TheOutputType == options::OT_DISABLE)
924 return LDPS_OK;
925
926 if (options::TheOutputType != options::OT_NORMAL) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000927 std::string path;
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000928 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000929 path = output_name;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000930 else
931 path = output_name + ".bc";
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000932 saveBCFile(path, *Combined);
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000933 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola55b32542014-08-11 19:06:54 +0000934 return LDPS_OK;
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000935 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000936
Peter Collingbourne87202a42015-09-01 20:40:22 +0000937 codegen(std::move(Combined));
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000938
Rafael Espindolaef498152010-06-23 20:20:59 +0000939 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000940 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
941 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000942
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000943 return LDPS_OK;
944}
945
Rafael Espindola55b32542014-08-11 19:06:54 +0000946static ld_plugin_status all_symbols_read_hook(void) {
947 ld_plugin_status Ret;
948 if (!options::generate_api_file) {
949 Ret = allSymbolsReadHook(nullptr);
950 } else {
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000951 std::error_code EC;
952 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
953 if (EC)
Rafael Espindola55b32542014-08-11 19:06:54 +0000954 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000955 EC.message().c_str());
Rafael Espindola33466a72014-08-21 20:28:55 +0000956 Ret = allSymbolsReadHook(&ApiFile);
Rafael Espindola55b32542014-08-11 19:06:54 +0000957 }
958
Rafael Espindola947bdb62014-11-25 20:52:49 +0000959 llvm_shutdown();
960
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000961 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000962 options::TheOutputType == options::OT_DISABLE) {
963 if (options::TheOutputType == options::OT_DISABLE)
964 // Remove the output file here since ld.bfd creates the output file
965 // early.
966 sys::fs::remove(output_name);
Rafael Espindola55b32542014-08-11 19:06:54 +0000967 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000968 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000969
970 return Ret;
971}
972
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000973static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000974 for (std::string &Name : Cleanup) {
975 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000976 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000977 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000978 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000979 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000980
981 return LDPS_OK;
982}