blob: f7379ea314abd600b634a22ef82412d8faaae691 [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"
Rafael Espindola503f8832015-03-02 19:08:03 +000023#include "llvm/IR/AutoUpgrade.h"
Rafael Espindola890db272014-09-09 20:08:22 +000024#include "llvm/IR/Constants.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000025#include "llvm/IR/DiagnosticInfo.h"
26#include "llvm/IR/DiagnosticPrinter.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000027#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000028#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000029#include "llvm/IR/Module.h"
30#include "llvm/IR/Verifier.h"
31#include "llvm/Linker/Linker.h"
32#include "llvm/MC/SubtargetFeature.h"
33#include "llvm/Object/IRObjectFile.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000034#include "llvm/Support/FormattedStream.h"
35#include "llvm/Support/Host.h"
Rafael Espindola947bdb62014-11-25 20:52:49 +000036#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000038#include "llvm/Support/TargetRegistry.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000039#include "llvm/Support/TargetSelect.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000040#include "llvm/Transforms/IPO.h"
41#include "llvm/Transforms/IPO/PassManagerBuilder.h"
42#include "llvm/Transforms/Utils/GlobalStatus.h"
43#include "llvm/Transforms/Utils/ModuleUtils.h"
Rafael Espindolaf7ecb112014-08-22 23:26:10 +000044#include "llvm/Transforms/Utils/ValueMapper.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000045#include <list>
Chandler Carruth07baed52014-01-13 08:04:33 +000046#include <plugin-api.h>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000047#include <system_error>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000048#include <vector>
49
Sylvestre Ledru53999792014-02-11 17:30:18 +000050#ifndef LDPO_PIE
51// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
52// Precise and Debian Wheezy (binutils 2.23 is required)
53# define LDPO_PIE 3
54#endif
55
Nick Lewyckyfb643e42009-02-03 07:13:24 +000056using namespace llvm;
57
58namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000059struct claimed_file {
60 void *handle;
61 std::vector<ld_plugin_symbol> syms;
62};
Nick Lewyckyfb643e42009-02-03 07:13:24 +000063}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000064
65static ld_plugin_status discard_message(int level, const char *format, ...) {
66 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
67 // callback in the transfer vector. This should never be called.
68 abort();
69}
70
Rafael Espindola33466a72014-08-21 20:28:55 +000071static ld_plugin_get_input_file get_input_file = nullptr;
72static ld_plugin_release_input_file release_input_file = nullptr;
Rafael Espindola176e6642014-07-29 21:46:05 +000073static ld_plugin_add_symbols add_symbols = nullptr;
74static ld_plugin_get_symbols get_symbols = nullptr;
75static ld_plugin_add_input_file add_input_file = nullptr;
76static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
77static ld_plugin_get_view get_view = nullptr;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000078static ld_plugin_message message = discard_message;
Rafael Espindola33466a72014-08-21 20:28:55 +000079static Reloc::Model RelocationModel = Reloc::Default;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000080static std::string output_name = "";
81static std::list<claimed_file> Modules;
82static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +000083static llvm::TargetOptions TargetOpts;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000084
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000085namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +000086 enum OutputType {
87 OT_NORMAL,
88 OT_DISABLE,
89 OT_BC_ONLY,
90 OT_SAVE_TEMPS
91 };
Dan Gohmanebb4ae02010-04-16 00:42:57 +000092 static bool generate_api_file = false;
Rafael Espindola6953a3a2014-11-24 21:18:14 +000093 static OutputType TheOutputType = OT_NORMAL;
Shuxin Yang1826ae22013-08-12 21:07:31 +000094 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +000095 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +000096 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +000097 static std::string mcpu;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000098 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +000099 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000100 // as plugin exclusive to pass to the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000101 // For example, "generate-api-file" and "as"options are for the plugin
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000102 // use only and will not be passed.
Rafael Espindola125b9242014-07-29 19:17:44 +0000103 static std::vector<const char *> extra;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000104
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000105 static void process_plugin_option(const char* opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000106 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000107 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000108 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000109 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000110
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000111 if (opt == "generate-api-file") {
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000112 generate_api_file = true;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000113 } else if (opt.startswith("mcpu=")) {
114 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000115 } else if (opt.startswith("extra-library-path=")) {
116 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000117 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000118 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000119 } else if (opt.startswith("obj-path=")) {
120 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000121 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000122 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000123 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000124 TheOutputType = OT_SAVE_TEMPS;
125 } else if (opt == "disable-output") {
126 TheOutputType = OT_DISABLE;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000127 } else {
128 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000129 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
130 // add that.
131 if (extra.empty())
132 extra.push_back("LLVMgold");
133
Rafael Espindola125b9242014-07-29 19:17:44 +0000134 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000135 }
136 }
137}
138
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000139static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
140 int *claimed);
141static ld_plugin_status all_symbols_read_hook(void);
142static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000143
144extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
145ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000146 InitializeAllTargetInfos();
147 InitializeAllTargets();
148 InitializeAllTargetMCs();
149 InitializeAllAsmParsers();
150 InitializeAllAsmPrinters();
151
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000152 // We're given a pointer to the first transfer vector. We read through them
153 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
154 // contain pointers to functions that we need to call to register our own
155 // hooks. The others are addresses of functions we can use to call into gold
156 // for services.
157
158 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000159 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000160
161 for (; tv->tv_tag != LDPT_NULL; ++tv) {
162 switch (tv->tv_tag) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000163 case LDPT_OUTPUT_NAME:
164 output_name = tv->tv_u.tv_string;
165 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000166 case LDPT_LINKER_OUTPUT:
167 switch (tv->tv_u.tv_val) {
168 case LDPO_REL: // .o
169 case LDPO_DYN: // .so
Rafael Espindola76e376d2014-02-10 20:38:38 +0000170 case LDPO_PIE: // position independent executable
Rafael Espindola33466a72014-08-21 20:28:55 +0000171 RelocationModel = Reloc::PIC_;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000172 break;
173 case LDPO_EXEC: // .exe
Rafael Espindola33466a72014-08-21 20:28:55 +0000174 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000175 break;
176 default:
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000177 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000178 return LDPS_ERR;
179 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000180 break;
181 case LDPT_OPTION:
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000182 options::process_plugin_option(tv->tv_u.tv_string);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000183 break;
184 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
185 ld_plugin_register_claim_file callback;
186 callback = tv->tv_u.tv_register_claim_file;
187
Rafael Espindola54f82b72014-07-30 01:36:32 +0000188 if (callback(claim_file_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000189 return LDPS_ERR;
190
191 registeredClaimFile = true;
192 } break;
193 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
194 ld_plugin_register_all_symbols_read callback;
195 callback = tv->tv_u.tv_register_all_symbols_read;
196
Rafael Espindola54f82b72014-07-30 01:36:32 +0000197 if (callback(all_symbols_read_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000198 return LDPS_ERR;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000199
Rafael Espindola6b244b12014-06-19 21:14:13 +0000200 RegisteredAllSymbolsRead = true;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000201 } break;
202 case LDPT_REGISTER_CLEANUP_HOOK: {
203 ld_plugin_register_cleanup callback;
204 callback = tv->tv_u.tv_register_cleanup;
205
Rafael Espindola54f82b72014-07-30 01:36:32 +0000206 if (callback(cleanup_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000207 return LDPS_ERR;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000208 } break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000209 case LDPT_GET_INPUT_FILE:
210 get_input_file = tv->tv_u.tv_get_input_file;
211 break;
212 case LDPT_RELEASE_INPUT_FILE:
213 release_input_file = tv->tv_u.tv_release_input_file;
214 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000215 case LDPT_ADD_SYMBOLS:
216 add_symbols = tv->tv_u.tv_add_symbols;
217 break;
Rafael Espindolacda29112013-10-03 18:29:09 +0000218 case LDPT_GET_SYMBOLS_V2:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000219 get_symbols = tv->tv_u.tv_get_symbols;
220 break;
221 case LDPT_ADD_INPUT_FILE:
222 add_input_file = tv->tv_u.tv_add_input_file;
223 break;
Rafael Espindolaef498152010-06-23 20:20:59 +0000224 case LDPT_SET_EXTRA_LIBRARY_PATH:
225 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
226 break;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000227 case LDPT_GET_VIEW:
228 get_view = tv->tv_u.tv_get_view;
229 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000230 case LDPT_MESSAGE:
231 message = tv->tv_u.tv_message;
232 break;
233 default:
234 break;
235 }
236 }
237
Rafael Espindolae08484d2009-02-18 08:30:15 +0000238 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000239 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000240 return LDPS_ERR;
241 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000242 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000243 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000244 return LDPS_ERR;
245 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000246
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000247 if (!RegisteredAllSymbolsRead)
248 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000249
Rafael Espindola33466a72014-08-21 20:28:55 +0000250 if (!get_input_file) {
251 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
252 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000253 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000254 if (!release_input_file) {
255 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
256 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000257 }
258
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000259 return LDPS_OK;
260}
261
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000262static const GlobalObject *getBaseObject(const GlobalValue &GV) {
263 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
264 return GA->getBaseObject();
265 return cast<GlobalObject>(&GV);
266}
267
Rafael Espindola527e8462014-12-09 16:13:59 +0000268static bool shouldSkip(uint32_t Symflags) {
269 if (!(Symflags & object::BasicSymbolRef::SF_Global))
270 return true;
271 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
272 return true;
273 return false;
274}
275
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000276static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
Rafael Espindola503f8832015-03-02 19:08:03 +0000277 if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
278 std::error_code EC = BDI->getError();
279 if (EC == BitcodeError::InvalidBitcodeSignature)
280 return;
281 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000282
283 std::string ErrStorage;
284 {
285 raw_string_ostream OS(ErrStorage);
286 DiagnosticPrinterRawOStream DP(OS);
287 DI.print(DP);
288 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000289 ld_plugin_level Level;
290 switch (DI.getSeverity()) {
291 case DS_Error:
292 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
293 ErrStorage.c_str());
294 llvm_unreachable("Fatal doesn't return.");
295 case DS_Warning:
296 Level = LDPL_WARNING;
297 break;
298 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000299 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000300 Level = LDPL_INFO;
301 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000302 }
303 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000304}
305
Rafael Espindolae54d8212014-07-06 14:31:22 +0000306/// Called by gold to see whether this file is one that our plugin can handle.
307/// We'll try to open it and register all the symbols with add_symbol if
308/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000309static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
310 int *claimed) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000311 LLVMContext Context;
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000312 MemoryBufferRef BufferRef;
313 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000314 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000315 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000316 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000317 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000318 return LDPS_ERR;
319 }
Rafael Espindolab0fc4cf2014-10-22 02:23:31 +0000320 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000321 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000322 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000323 // Gold has found what might be IR part-way inside of a file, such as
324 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000325 if (file->offset) {
326 offset = file->offset;
327 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000328 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
329 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
330 offset);
331 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000332 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000333 return LDPS_ERR;
334 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000335 Buffer = std::move(BufferOrErr.get());
336 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000337 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000338
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000339 Context.setDiagnosticHandler(diagnosticHandler);
David Blaikie10a27df2014-09-03 17:59:23 +0000340 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000341 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola33466a72014-08-21 20:28:55 +0000342 std::error_code EC = ObjOrErr.getError();
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000343 if (EC == object::object_error::invalid_file_type ||
Peter Collingbourne10039c02014-09-18 21:28:49 +0000344 EC == object::object_error::bitcode_section_not_found)
Ivan Krasin5021af52011-09-12 21:47:50 +0000345 return LDPS_OK;
346
Rafael Espindola6c472e52014-07-29 20:46:19 +0000347 *claimed = 1;
348
Rafael Espindola33466a72014-08-21 20:28:55 +0000349 if (EC) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000350 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000351 EC.message().c_str());
Rafael Espindola6c472e52014-07-29 20:46:19 +0000352 return LDPS_ERR;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000353 }
David Blaikie10a27df2014-09-03 17:59:23 +0000354 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000355
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000356 Modules.resize(Modules.size() + 1);
357 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000358
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000359 cf.handle = file->handle;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000360
Rafael Espindola33466a72014-08-21 20:28:55 +0000361 for (auto &Sym : Obj->symbols()) {
362 uint32_t Symflags = Sym.getFlags();
Rafael Espindola527e8462014-12-09 16:13:59 +0000363 if (shouldSkip(Symflags))
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000364 continue;
365
366 cf.syms.push_back(ld_plugin_symbol());
367 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000368 sym.version = nullptr;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000369
Rafael Espindola33466a72014-08-21 20:28:55 +0000370 SmallString<64> Name;
371 {
372 raw_svector_ostream OS(Name);
373 Sym.printName(OS);
374 }
375 sym.name = strdup(Name.c_str());
376
377 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
378
379 sym.visibility = LDPV_DEFAULT;
380 if (GV) {
381 switch (GV->getVisibility()) {
382 case GlobalValue::DefaultVisibility:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000383 sym.visibility = LDPV_DEFAULT;
384 break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000385 case GlobalValue::HiddenVisibility:
386 sym.visibility = LDPV_HIDDEN;
387 break;
388 case GlobalValue::ProtectedVisibility:
389 sym.visibility = LDPV_PROTECTED;
390 break;
391 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000392 }
393
Rafael Espindola33466a72014-08-21 20:28:55 +0000394 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
395 sym.def = LDPK_UNDEF;
396 if (GV && GV->hasExternalWeakLinkage())
Rafael Espindola56548522009-04-24 16:55:21 +0000397 sym.def = LDPK_WEAKUNDEF;
Rafael Espindola33466a72014-08-21 20:28:55 +0000398 } else {
399 sym.def = LDPK_DEF;
400 if (GV) {
401 assert(!GV->hasExternalWeakLinkage() &&
402 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
403 if (GV->hasCommonLinkage())
404 sym.def = LDPK_COMMON;
405 else if (GV->isWeakForLinker())
406 sym.def = LDPK_WEAKDEF;
407 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000408 }
409
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000410 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000411 sym.comdat_key = nullptr;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000412 if (GV) {
413 const GlobalObject *Base = getBaseObject(*GV);
414 if (!Base)
415 message(LDPL_FATAL, "Unable to determine comdat of alias!");
416 const Comdat *C = Base->getComdat();
417 if (C)
418 sym.comdat_key = strdup(C->getName().str().c_str());
419 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
420 sym.comdat_key = strdup(sym.name);
421 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000422
423 sym.resolution = LDPR_UNKNOWN;
424 }
425
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000426 if (!cf.syms.empty()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000427 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
428 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000429 return LDPS_ERR;
430 }
431 }
432
433 return LDPS_OK;
434}
435
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000436static void keepGlobalValue(GlobalValue &GV,
437 std::vector<GlobalAlias *> &KeptAliases) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000438 assert(!GV.hasLocalLinkage());
439
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000440 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
441 KeptAliases.push_back(GA);
442
Rafael Espindola33466a72014-08-21 20:28:55 +0000443 switch (GV.getLinkage()) {
444 default:
445 break;
446 case GlobalValue::LinkOnceAnyLinkage:
447 GV.setLinkage(GlobalValue::WeakAnyLinkage);
448 break;
449 case GlobalValue::LinkOnceODRLinkage:
450 GV.setLinkage(GlobalValue::WeakODRLinkage);
451 break;
452 }
453
454 assert(!GV.isDiscardableIfUnused());
455}
456
Rafael Espindola33466a72014-08-21 20:28:55 +0000457static void internalize(GlobalValue &GV) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000458 if (GV.isDeclarationForLinker())
Rafael Espindola33466a72014-08-21 20:28:55 +0000459 return; // We get here if there is a matching asm definition.
460 if (!GV.hasLocalLinkage())
461 GV.setLinkage(GlobalValue::InternalLinkage);
462}
463
464static void drop(GlobalValue &GV) {
465 if (auto *F = dyn_cast<Function>(&GV)) {
466 F->deleteBody();
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000467 F->setComdat(nullptr); // Should deleteBody do this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000468 return;
469 }
470
471 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
472 Var->setInitializer(nullptr);
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000473 Var->setLinkage(
474 GlobalValue::ExternalLinkage); // Should setInitializer do this?
475 Var->setComdat(nullptr); // and this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000476 return;
477 }
478
479 auto &Alias = cast<GlobalAlias>(GV);
480 Module &M = *Alias.getParent();
481 PointerType &Ty = *cast<PointerType>(Alias.getType());
482 GlobalValue::LinkageTypes L = Alias.getLinkage();
483 auto *Var =
484 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
485 /*Initializer*/ nullptr);
486 Var->takeName(&Alias);
487 Alias.replaceAllUsesWith(Var);
Rafael Espindola71143ed2014-09-10 19:39:41 +0000488 Alias.eraseFromParent();
Rafael Espindola33466a72014-08-21 20:28:55 +0000489}
490
491static const char *getResolutionName(ld_plugin_symbol_resolution R) {
492 switch (R) {
493 case LDPR_UNKNOWN:
494 return "UNKNOWN";
495 case LDPR_UNDEF:
496 return "UNDEF";
497 case LDPR_PREVAILING_DEF:
498 return "PREVAILING_DEF";
499 case LDPR_PREVAILING_DEF_IRONLY:
500 return "PREVAILING_DEF_IRONLY";
501 case LDPR_PREEMPTED_REG:
502 return "PREEMPTED_REG";
503 case LDPR_PREEMPTED_IR:
504 return "PREEMPTED_IR";
505 case LDPR_RESOLVED_IR:
506 return "RESOLVED_IR";
507 case LDPR_RESOLVED_EXEC:
508 return "RESOLVED_EXEC";
509 case LDPR_RESOLVED_DYN:
510 return "RESOLVED_DYN";
511 case LDPR_PREVAILING_DEF_IRONLY_EXP:
512 return "PREVAILING_DEF_IRONLY_EXP";
513 }
Rafael Espindola2754dbb2014-10-10 00:48:13 +0000514 llvm_unreachable("Unknown resolution");
Rafael Espindola33466a72014-08-21 20:28:55 +0000515}
516
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000517namespace {
518class LocalValueMaterializer : public ValueMaterializer {
519 DenseSet<GlobalValue *> &Dropped;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000520 DenseMap<GlobalObject *, GlobalObject *> LocalVersions;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000521
522public:
523 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
524 Value *materializeValueFor(Value *V) override;
525};
526}
527
528Value *LocalValueMaterializer::materializeValueFor(Value *V) {
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000529 auto *GO = dyn_cast<GlobalObject>(V);
530 if (!GO)
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000531 return nullptr;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000532
533 auto I = LocalVersions.find(GO);
534 if (I != LocalVersions.end())
535 return I->second;
536
537 if (!Dropped.count(GO))
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000538 return nullptr;
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000539
540 Module &M = *GO->getParent();
541 GlobalValue::LinkageTypes L = GO->getLinkage();
542 GlobalObject *Declaration;
543 if (auto *F = dyn_cast<Function>(GO)) {
544 Declaration = Function::Create(F->getFunctionType(), L, "", &M);
545 } else {
546 auto *Var = cast<GlobalVariable>(GO);
547 Declaration = new GlobalVariable(M, Var->getType()->getElementType(),
548 Var->isConstant(), L,
549 /*Initializer*/ nullptr);
550 }
551 Declaration->takeName(GO);
552 Declaration->copyAttributesFrom(GO);
553
554 GO->setLinkage(GlobalValue::InternalLinkage);
555 GO->setName(Declaration->getName());
556 Dropped.erase(GO);
557 GO->replaceAllUsesWith(Declaration);
558
559 LocalVersions[Declaration] = GO;
560
561 return GO;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000562}
563
564static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
565 LocalValueMaterializer *Materializer) {
566 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
567}
568
Rafael Espindola538c9a82014-12-23 18:18:37 +0000569static void freeSymName(ld_plugin_symbol &Sym) {
570 free(Sym.name);
571 free(Sym.comdat_key);
572 Sym.name = nullptr;
573 Sym.comdat_key = nullptr;
574}
575
Rafael Espindola33466a72014-08-21 20:28:55 +0000576static std::unique_ptr<Module>
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000577getModuleForFile(LLVMContext &Context, claimed_file &F,
Rafael Espindola503f8832015-03-02 19:08:03 +0000578 ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
Rafael Espindola33466a72014-08-21 20:28:55 +0000579 StringSet<> &Internalize, StringSet<> &Maybe) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000580
581 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
582 message(LDPL_FATAL, "Failed to get symbol information");
583
584 const void *View;
585 if (get_view(F.handle, &View) != LDPS_OK)
586 message(LDPL_FATAL, "Failed to get a view of file");
587
Rafael Espindola503f8832015-03-02 19:08:03 +0000588 MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
589 Info.name);
Rafael Espindola527e8462014-12-09 16:13:59 +0000590 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindola5dec7ea2014-12-09 20:36:13 +0000591 object::IRObjectFile::create(BufferRef, Context);
Rafael Espindola527e8462014-12-09 16:13:59 +0000592
593 if (std::error_code EC = ObjOrErr.getError())
Peter Collingbourne10039c02014-09-18 21:28:49 +0000594 message(LDPL_FATAL, "Could not read bitcode from file : %s",
595 EC.message().c_str());
596
Rafael Espindola527e8462014-12-09 16:13:59 +0000597 object::IRObjectFile &Obj = **ObjOrErr;
Rafael Espindola33466a72014-08-21 20:28:55 +0000598
Rafael Espindola527e8462014-12-09 16:13:59 +0000599 Module &M = Obj.getModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000600
Rafael Espindola503f8832015-03-02 19:08:03 +0000601 UpgradeDebugInfo(M);
602
Rafael Espindola33466a72014-08-21 20:28:55 +0000603 SmallPtrSet<GlobalValue *, 8> Used;
Rafael Espindola527e8462014-12-09 16:13:59 +0000604 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
Rafael Espindola33466a72014-08-21 20:28:55 +0000605
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000606 DenseSet<GlobalValue *> Drop;
607 std::vector<GlobalAlias *> KeptAliases;
Rafael Espindola527e8462014-12-09 16:13:59 +0000608
609 unsigned SymNum = 0;
610 for (auto &ObjSym : Obj.symbols()) {
611 if (shouldSkip(ObjSym.getFlags()))
612 continue;
613 ld_plugin_symbol &Sym = F.syms[SymNum];
614 ++SymNum;
615
Rafael Espindola33466a72014-08-21 20:28:55 +0000616 ld_plugin_symbol_resolution Resolution =
617 (ld_plugin_symbol_resolution)Sym.resolution;
618
619 if (options::generate_api_file)
620 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
621
Rafael Espindola527e8462014-12-09 16:13:59 +0000622 GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
Rafael Espindola538c9a82014-12-23 18:18:37 +0000623 if (!GV) {
624 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000625 continue; // Asm symbol.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000626 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000627
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000628 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
Rafael Espindola890db272014-09-09 20:08:22 +0000629 // Common linkage is special. There is no single symbol that wins the
630 // resolution. Instead we have to collect the maximum alignment and size.
631 // The IR linker does that for us if we just pass it every common GV.
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000632 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
633 // internalize once the IR linker has done its job.
Rafael Espindola538c9a82014-12-23 18:18:37 +0000634 freeSymName(Sym);
Rafael Espindola890db272014-09-09 20:08:22 +0000635 continue;
636 }
637
Rafael Espindola33466a72014-08-21 20:28:55 +0000638 switch (Resolution) {
639 case LDPR_UNKNOWN:
640 llvm_unreachable("Unexpected resolution");
641
642 case LDPR_RESOLVED_IR:
643 case LDPR_RESOLVED_EXEC:
644 case LDPR_RESOLVED_DYN:
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000645 assert(GV->isDeclarationForLinker());
Rafael Espindola33466a72014-08-21 20:28:55 +0000646 break;
647
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000648 case LDPR_UNDEF:
Rafael Espindola9e3e53f2015-01-14 20:08:46 +0000649 if (!GV->isDeclarationForLinker()) {
Rafael Espindola0fd9e5f2015-01-14 19:43:32 +0000650 assert(GV->hasComdat());
651 Drop.insert(GV);
652 }
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000653 break;
654
Rafael Espindola33466a72014-08-21 20:28:55 +0000655 case LDPR_PREVAILING_DEF_IRONLY: {
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000656 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000657 if (!Used.count(GV)) {
658 // Since we use the regular lib/Linker, we cannot just internalize GV
659 // now or it will not be copied to the merged module. Instead we force
660 // it to be copied and then internalize it.
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000661 Internalize.insert(GV->getName());
Rafael Espindola33466a72014-08-21 20:28:55 +0000662 }
663 break;
664 }
665
666 case LDPR_PREVAILING_DEF:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000667 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000668 break;
669
Rafael Espindola33466a72014-08-21 20:28:55 +0000670 case LDPR_PREEMPTED_IR:
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000671 // Gold might have selected a linkonce_odr and preempted a weak_odr.
672 // In that case we have to make sure we don't end up internalizing it.
673 if (!GV->isDiscardableIfUnused())
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000674 Maybe.erase(GV->getName());
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000675
676 // fall-through
677 case LDPR_PREEMPTED_REG:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000678 Drop.insert(GV);
Rafael Espindola33466a72014-08-21 20:28:55 +0000679 break;
680
681 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
682 // We can only check for address uses after we merge the modules. The
683 // reason is that this GV might have a copy in another module
684 // and in that module the address might be significant, but that
685 // copy will be LDPR_PREEMPTED_IR.
686 if (GV->hasLinkOnceODRLinkage())
Rafael Espindolaa4f104b2014-12-09 16:50:57 +0000687 Maybe.insert(GV->getName());
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000688 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000689 break;
690 }
691 }
692
Rafael Espindola538c9a82014-12-23 18:18:37 +0000693 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000694 }
695
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000696 ValueToValueMapTy VM;
697 LocalValueMaterializer Materializer(Drop);
698 for (GlobalAlias *GA : KeptAliases) {
699 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
700 // expression is being dropped. If that is the case, that GV must be copied.
701 Constant *Aliasee = GA->getAliasee();
702 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
Rafael Espindola4d47f7f2014-12-10 00:09:35 +0000703 GA->setAliasee(Replacement);
Rafael Espindola33466a72014-08-21 20:28:55 +0000704 }
705
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000706 for (auto *GV : Drop)
707 drop(*GV);
708
Rafael Espindola527e8462014-12-09 16:13:59 +0000709 return Obj.takeModule();
Rafael Espindola33466a72014-08-21 20:28:55 +0000710}
711
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000712static void runLTOPasses(Module &M, TargetMachine &TM) {
Rafael Espindola85d85092015-02-21 00:13:15 +0000713 if (const DataLayout *DL = TM.getDataLayout())
Rafael Espindola265ffbe2015-03-04 19:15:29 +0000714 M.setDataLayout(*DL);
Rafael Espindola85d85092015-02-21 00:13:15 +0000715
Chandler Carruth30d69c22015-02-13 10:01:29 +0000716 legacy::PassManager passes;
NAKAMURA Takumib0a52832015-02-02 05:47:30 +0000717 passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
718
Chandler Carruth5700b372015-02-13 21:10:58 +0000719 PassManagerBuilder PMB;
Sylvestre Ledru450f97d2015-01-24 13:59:08 +0000720 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
Rafael Espindola33466a72014-08-21 20:28:55 +0000721 PMB.Inliner = createFunctionInliningPass();
722 PMB.VerifyInput = true;
723 PMB.VerifyOutput = true;
Rafael Espindola8391dbd2014-10-30 00:11:24 +0000724 PMB.LoopVectorize = true;
Rafael Espindola919fb532014-10-30 00:38:54 +0000725 PMB.SLPVectorize = true;
Alexey Samsonov5ce24482015-01-30 19:14:04 +0000726 PMB.populateLTOPassManager(passes);
Rafael Espindola33466a72014-08-21 20:28:55 +0000727 passes.run(M);
728}
729
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000730static void saveBCFile(StringRef Path, Module &M) {
731 std::error_code EC;
732 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
733 if (EC)
734 message(LDPL_FATAL, "Failed to write the output file.");
735 WriteBitcodeToFile(&M, OS);
736}
737
Rafael Espindola33466a72014-08-21 20:28:55 +0000738static void codegen(Module &M) {
739 const std::string &TripleStr = M.getTargetTriple();
740 Triple TheTriple(TripleStr);
741
742 std::string ErrMsg;
743 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
744 if (!TheTarget)
745 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
746
747 if (unsigned NumOpts = options::extra.size())
748 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
749
750 SubtargetFeatures Features;
751 Features.getDefaultSubtargetFeatures(TheTriple);
752 for (const std::string &A : MAttrs)
753 Features.AddFeature(A);
754
755 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
756 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
757 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
758 CodeModel::Default, CodeGenOpt::Aggressive));
759
760 runLTOPasses(M, *TM);
761
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000762 if (options::TheOutputType == options::OT_SAVE_TEMPS)
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000763 saveBCFile(output_name + ".opt.bc", M);
764
Chandler Carruth30d69c22015-02-13 10:01:29 +0000765 legacy::PassManager CodeGenPasses;
Rafael Espindola33466a72014-08-21 20:28:55 +0000766
767 SmallString<128> Filename;
768 int FD;
769 if (options::obj_path.empty()) {
770 std::error_code EC =
771 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
772 if (EC)
Duncan P. N. Exon Smithf6ab4702014-11-19 22:39:21 +0000773 message(LDPL_FATAL, "Could not create temporary file: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000774 EC.message().c_str());
775 } else {
776 Filename = options::obj_path;
777 std::error_code EC =
778 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
779 if (EC)
780 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
781 }
782
783 {
784 raw_fd_ostream OS(FD, true);
785 formatted_raw_ostream FOS(OS);
786
787 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
788 TargetMachine::CGFT_ObjectFile))
789 message(LDPL_FATAL, "Failed to setup codegen");
790 CodeGenPasses.run(M);
791 }
792
793 if (add_input_file(Filename.c_str()) != LDPS_OK)
794 message(LDPL_FATAL,
795 "Unable to add .o file to the link. File left behind in: %s",
796 Filename.c_str());
797
798 if (options::obj_path.empty())
799 Cleanup.push_back(Filename.c_str());
Rafael Espindola282a4702013-10-31 20:51:58 +0000800}
801
Rafael Espindolab6393292014-07-30 01:23:45 +0000802/// gold informs us that all symbols have been read. At this point, we use
803/// get_symbols to see if any of our definitions have been overridden by a
804/// native object file. Then, perform optimization and codegen.
Rafael Espindola33466a72014-08-21 20:28:55 +0000805static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
806 if (Modules.empty())
807 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000808
Rafael Espindola33466a72014-08-21 20:28:55 +0000809 LLVMContext Context;
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000810 Context.setDiagnosticHandler(diagnosticHandler, nullptr, true);
Rafael Espindola503f8832015-03-02 19:08:03 +0000811
Rafael Espindola33466a72014-08-21 20:28:55 +0000812 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
813 Linker L(Combined.get());
814
815 std::string DefaultTriple = sys::getDefaultTargetTriple();
816
817 StringSet<> Internalize;
818 StringSet<> Maybe;
Rafael Espindolad2aac572014-07-30 01:52:40 +0000819 for (claimed_file &F : Modules) {
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000820 ld_plugin_input_file File;
821 if (get_input_file(F.handle, &File) != LDPS_OK)
822 message(LDPL_FATAL, "Failed to get file information");
Rafael Espindola33466a72014-08-21 20:28:55 +0000823 std::unique_ptr<Module> M =
Rafael Espindola503f8832015-03-02 19:08:03 +0000824 getModuleForFile(Context, F, File, ApiFile, Internalize, Maybe);
Rafael Espindola33466a72014-08-21 20:28:55 +0000825 if (!options::triple.empty())
826 M->setTargetTriple(options::triple.c_str());
827 else if (M->getTargetTriple().empty()) {
828 M->setTargetTriple(DefaultTriple);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000829 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000830
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000831 if (L.linkInModule(M.get()))
832 message(LDPL_FATAL, "Failed to link module");
Jan Wen Voungc11b45a2015-02-11 16:12:50 +0000833 if (release_input_file(F.handle) != LDPS_OK)
834 message(LDPL_FATAL, "Failed to release file information");
Rafael Espindola77b6d012010-06-14 21:20:52 +0000835 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000836
Rafael Espindola33466a72014-08-21 20:28:55 +0000837 for (const auto &Name : Internalize) {
838 GlobalValue *GV = Combined->getNamedValue(Name.first());
839 if (GV)
840 internalize(*GV);
841 }
842
843 for (const auto &Name : Maybe) {
844 GlobalValue *GV = Combined->getNamedValue(Name.first());
845 if (!GV)
846 continue;
847 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
848 if (canBeOmittedFromSymbolTable(GV))
849 internalize(*GV);
850 }
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000851
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000852 if (options::TheOutputType == options::OT_DISABLE)
853 return LDPS_OK;
854
855 if (options::TheOutputType != options::OT_NORMAL) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000856 std::string path;
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000857 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000858 path = output_name;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000859 else
860 path = output_name + ".bc";
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000861 saveBCFile(path, *L.getModule());
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000862 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola55b32542014-08-11 19:06:54 +0000863 return LDPS_OK;
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000864 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000865
Rafael Espindola33466a72014-08-21 20:28:55 +0000866 codegen(*L.getModule());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000867
Rafael Espindolaef498152010-06-23 20:20:59 +0000868 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000869 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
870 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000871
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000872 return LDPS_OK;
873}
874
Rafael Espindola55b32542014-08-11 19:06:54 +0000875static ld_plugin_status all_symbols_read_hook(void) {
876 ld_plugin_status Ret;
877 if (!options::generate_api_file) {
878 Ret = allSymbolsReadHook(nullptr);
879 } else {
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000880 std::error_code EC;
881 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
882 if (EC)
Rafael Espindola55b32542014-08-11 19:06:54 +0000883 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000884 EC.message().c_str());
Rafael Espindola33466a72014-08-21 20:28:55 +0000885 Ret = allSymbolsReadHook(&ApiFile);
Rafael Espindola55b32542014-08-11 19:06:54 +0000886 }
887
Rafael Espindola947bdb62014-11-25 20:52:49 +0000888 llvm_shutdown();
889
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000890 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000891 options::TheOutputType == options::OT_DISABLE) {
892 if (options::TheOutputType == options::OT_DISABLE)
893 // Remove the output file here since ld.bfd creates the output file
894 // early.
895 sys::fs::remove(output_name);
Rafael Espindola55b32542014-08-11 19:06:54 +0000896 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +0000897 }
Rafael Espindola55b32542014-08-11 19:06:54 +0000898
899 return Ret;
900}
901
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000902static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000903 for (std::string &Name : Cleanup) {
904 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000905 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000906 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000907 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000908 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000909
910 return LDPS_OK;
911}