blob: b7d8c5e14c688ee3fc350a992742aa41cba3b79a [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"
Rafael Espindola33466a72014-08-21 20:28:55 +000018#include "llvm/Bitcode/ReaderWriter.h"
19#include "llvm/CodeGen/Analysis.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000020#include "llvm/CodeGen/CommandFlags.h"
Rafael Espindola890db272014-09-09 20:08:22 +000021#include "llvm/IR/Constants.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000022#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Verifier.h"
25#include "llvm/Linker/Linker.h"
26#include "llvm/MC/SubtargetFeature.h"
27#include "llvm/Object/IRObjectFile.h"
28#include "llvm/PassManager.h"
29#include "llvm/Support/FormattedStream.h"
30#include "llvm/Support/Host.h"
Rafael Espindola947bdb62014-11-25 20:52:49 +000031#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000032#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000033#include "llvm/Support/TargetRegistry.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000034#include "llvm/Support/TargetSelect.h"
Rafael Espindola33466a72014-08-21 20:28:55 +000035#include "llvm/Target/TargetLibraryInfo.h"
36#include "llvm/Transforms/IPO.h"
37#include "llvm/Transforms/IPO/PassManagerBuilder.h"
38#include "llvm/Transforms/Utils/GlobalStatus.h"
39#include "llvm/Transforms/Utils/ModuleUtils.h"
Rafael Espindolaf7ecb112014-08-22 23:26:10 +000040#include "llvm/Transforms/Utils/ValueMapper.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000041#include <list>
Chandler Carruth07baed52014-01-13 08:04:33 +000042#include <plugin-api.h>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000043#include <system_error>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000044#include <vector>
45
Sylvestre Ledru53999792014-02-11 17:30:18 +000046#ifndef LDPO_PIE
47// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
48// Precise and Debian Wheezy (binutils 2.23 is required)
49# define LDPO_PIE 3
50#endif
51
Nick Lewyckyfb643e42009-02-03 07:13:24 +000052using namespace llvm;
53
54namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000055struct claimed_file {
56 void *handle;
57 std::vector<ld_plugin_symbol> syms;
58};
Nick Lewyckyfb643e42009-02-03 07:13:24 +000059}
Rafael Espindolabfb8b912014-06-20 01:37:35 +000060
61static ld_plugin_status discard_message(int level, const char *format, ...) {
62 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
63 // callback in the transfer vector. This should never be called.
64 abort();
65}
66
Rafael Espindola33466a72014-08-21 20:28:55 +000067static ld_plugin_get_input_file get_input_file = nullptr;
68static ld_plugin_release_input_file release_input_file = nullptr;
Rafael Espindola176e6642014-07-29 21:46:05 +000069static ld_plugin_add_symbols add_symbols = nullptr;
70static ld_plugin_get_symbols get_symbols = nullptr;
71static ld_plugin_add_input_file add_input_file = nullptr;
72static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
73static ld_plugin_get_view get_view = nullptr;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000074static ld_plugin_message message = discard_message;
Rafael Espindola33466a72014-08-21 20:28:55 +000075static Reloc::Model RelocationModel = Reloc::Default;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000076static std::string output_name = "";
77static std::list<claimed_file> Modules;
78static std::vector<std::string> Cleanup;
Rafael Espindola6b244b12014-06-19 21:14:13 +000079static llvm::TargetOptions TargetOpts;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000080
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000081namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +000082 enum OutputType {
83 OT_NORMAL,
84 OT_DISABLE,
85 OT_BC_ONLY,
86 OT_SAVE_TEMPS
87 };
Dan Gohmanebb4ae02010-04-16 00:42:57 +000088 static bool generate_api_file = false;
Rafael Espindola6953a3a2014-11-24 21:18:14 +000089 static OutputType TheOutputType = OT_NORMAL;
Shuxin Yang1826ae22013-08-12 21:07:31 +000090 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +000091 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +000092 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +000093 static std::string mcpu;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000094 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +000095 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000096 // as plugin exclusive to pass to the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +000097 // For example, "generate-api-file" and "as"options are for the plugin
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +000098 // use only and will not be passed.
Rafael Espindola125b9242014-07-29 19:17:44 +000099 static std::vector<const char *> extra;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000100
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000101 static void process_plugin_option(const char* opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000102 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000103 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000104 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000105 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000106
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000107 if (opt == "generate-api-file") {
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000108 generate_api_file = true;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000109 } else if (opt.startswith("mcpu=")) {
110 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000111 } else if (opt.startswith("extra-library-path=")) {
112 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000113 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000114 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000115 } else if (opt.startswith("obj-path=")) {
116 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000117 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000118 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000119 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000120 TheOutputType = OT_SAVE_TEMPS;
121 } else if (opt == "disable-output") {
122 TheOutputType = OT_DISABLE;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000123 } else {
124 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000125 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
126 // add that.
127 if (extra.empty())
128 extra.push_back("LLVMgold");
129
Rafael Espindola125b9242014-07-29 19:17:44 +0000130 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000131 }
132 }
133}
134
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000135static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
136 int *claimed);
137static ld_plugin_status all_symbols_read_hook(void);
138static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000139
140extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
141ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000142 InitializeAllTargetInfos();
143 InitializeAllTargets();
144 InitializeAllTargetMCs();
145 InitializeAllAsmParsers();
146 InitializeAllAsmPrinters();
147
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000148 // We're given a pointer to the first transfer vector. We read through them
149 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
150 // contain pointers to functions that we need to call to register our own
151 // hooks. The others are addresses of functions we can use to call into gold
152 // for services.
153
154 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000155 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000156
157 for (; tv->tv_tag != LDPT_NULL; ++tv) {
158 switch (tv->tv_tag) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000159 case LDPT_OUTPUT_NAME:
160 output_name = tv->tv_u.tv_string;
161 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000162 case LDPT_LINKER_OUTPUT:
163 switch (tv->tv_u.tv_val) {
164 case LDPO_REL: // .o
165 case LDPO_DYN: // .so
Rafael Espindola76e376d2014-02-10 20:38:38 +0000166 case LDPO_PIE: // position independent executable
Rafael Espindola33466a72014-08-21 20:28:55 +0000167 RelocationModel = Reloc::PIC_;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000168 break;
169 case LDPO_EXEC: // .exe
Rafael Espindola33466a72014-08-21 20:28:55 +0000170 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000171 break;
172 default:
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000173 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000174 return LDPS_ERR;
175 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000176 break;
177 case LDPT_OPTION:
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000178 options::process_plugin_option(tv->tv_u.tv_string);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000179 break;
180 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
181 ld_plugin_register_claim_file callback;
182 callback = tv->tv_u.tv_register_claim_file;
183
Rafael Espindola54f82b72014-07-30 01:36:32 +0000184 if (callback(claim_file_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000185 return LDPS_ERR;
186
187 registeredClaimFile = true;
188 } break;
189 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
190 ld_plugin_register_all_symbols_read callback;
191 callback = tv->tv_u.tv_register_all_symbols_read;
192
Rafael Espindola54f82b72014-07-30 01:36:32 +0000193 if (callback(all_symbols_read_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000194 return LDPS_ERR;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000195
Rafael Espindola6b244b12014-06-19 21:14:13 +0000196 RegisteredAllSymbolsRead = true;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000197 } break;
198 case LDPT_REGISTER_CLEANUP_HOOK: {
199 ld_plugin_register_cleanup callback;
200 callback = tv->tv_u.tv_register_cleanup;
201
Rafael Espindola54f82b72014-07-30 01:36:32 +0000202 if (callback(cleanup_hook) != LDPS_OK)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000203 return LDPS_ERR;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000204 } break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000205 case LDPT_GET_INPUT_FILE:
206 get_input_file = tv->tv_u.tv_get_input_file;
207 break;
208 case LDPT_RELEASE_INPUT_FILE:
209 release_input_file = tv->tv_u.tv_release_input_file;
210 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000211 case LDPT_ADD_SYMBOLS:
212 add_symbols = tv->tv_u.tv_add_symbols;
213 break;
Rafael Espindolacda29112013-10-03 18:29:09 +0000214 case LDPT_GET_SYMBOLS_V2:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000215 get_symbols = tv->tv_u.tv_get_symbols;
216 break;
217 case LDPT_ADD_INPUT_FILE:
218 add_input_file = tv->tv_u.tv_add_input_file;
219 break;
Rafael Espindolaef498152010-06-23 20:20:59 +0000220 case LDPT_SET_EXTRA_LIBRARY_PATH:
221 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
222 break;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000223 case LDPT_GET_VIEW:
224 get_view = tv->tv_u.tv_get_view;
225 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000226 case LDPT_MESSAGE:
227 message = tv->tv_u.tv_message;
228 break;
229 default:
230 break;
231 }
232 }
233
Rafael Espindolae08484d2009-02-18 08:30:15 +0000234 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000235 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000236 return LDPS_ERR;
237 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000238 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000239 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000240 return LDPS_ERR;
241 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000242
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000243 if (!RegisteredAllSymbolsRead)
244 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000245
Rafael Espindola33466a72014-08-21 20:28:55 +0000246 if (!get_input_file) {
247 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
248 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000249 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000250 if (!release_input_file) {
251 message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
252 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000253 }
254
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000255 return LDPS_OK;
256}
257
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000258static const GlobalObject *getBaseObject(const GlobalValue &GV) {
259 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
260 return GA->getBaseObject();
261 return cast<GlobalObject>(&GV);
262}
263
Rafael Espindolae54d8212014-07-06 14:31:22 +0000264/// Called by gold to see whether this file is one that our plugin can handle.
265/// We'll try to open it and register all the symbols with add_symbol if
266/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000267static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
268 int *claimed) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000269 LLVMContext Context;
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000270 MemoryBufferRef BufferRef;
271 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000272 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000273 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000274 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000275 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000276 return LDPS_ERR;
277 }
Rafael Espindolab0fc4cf2014-10-22 02:23:31 +0000278 BufferRef = MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000279 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000280 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000281 // Gold has found what might be IR part-way inside of a file, such as
282 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000283 if (file->offset) {
284 offset = file->offset;
285 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000286 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
287 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
288 offset);
289 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000290 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000291 return LDPS_ERR;
292 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000293 Buffer = std::move(BufferOrErr.get());
294 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000295 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000296
David Blaikie10a27df2014-09-03 17:59:23 +0000297 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000298 object::IRObjectFile::createIRObjectFile(BufferRef, Context);
Rafael Espindola33466a72014-08-21 20:28:55 +0000299 std::error_code EC = ObjOrErr.getError();
Peter Collingbourne10039c02014-09-18 21:28:49 +0000300 if (EC == BitcodeError::InvalidBitcodeSignature ||
301 EC == object::object_error::invalid_file_type ||
302 EC == object::object_error::bitcode_section_not_found)
Ivan Krasin5021af52011-09-12 21:47:50 +0000303 return LDPS_OK;
304
Rafael Espindola6c472e52014-07-29 20:46:19 +0000305 *claimed = 1;
306
Rafael Espindola33466a72014-08-21 20:28:55 +0000307 if (EC) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000308 message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000309 EC.message().c_str());
Rafael Espindola6c472e52014-07-29 20:46:19 +0000310 return LDPS_ERR;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000311 }
David Blaikie10a27df2014-09-03 17:59:23 +0000312 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000313
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000314 Modules.resize(Modules.size() + 1);
315 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000316
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000317 cf.handle = file->handle;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000318
Rafael Espindola33466a72014-08-21 20:28:55 +0000319 for (auto &Sym : Obj->symbols()) {
320 uint32_t Symflags = Sym.getFlags();
321 if (!(Symflags & object::BasicSymbolRef::SF_Global))
322 continue;
323
324 if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000325 continue;
326
327 cf.syms.push_back(ld_plugin_symbol());
328 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000329 sym.version = nullptr;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000330
Rafael Espindola33466a72014-08-21 20:28:55 +0000331 SmallString<64> Name;
332 {
333 raw_svector_ostream OS(Name);
334 Sym.printName(OS);
335 }
336 sym.name = strdup(Name.c_str());
337
338 const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
339
340 sym.visibility = LDPV_DEFAULT;
341 if (GV) {
342 switch (GV->getVisibility()) {
343 case GlobalValue::DefaultVisibility:
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000344 sym.visibility = LDPV_DEFAULT;
345 break;
Rafael Espindola33466a72014-08-21 20:28:55 +0000346 case GlobalValue::HiddenVisibility:
347 sym.visibility = LDPV_HIDDEN;
348 break;
349 case GlobalValue::ProtectedVisibility:
350 sym.visibility = LDPV_PROTECTED;
351 break;
352 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000353 }
354
Rafael Espindola33466a72014-08-21 20:28:55 +0000355 if (Symflags & object::BasicSymbolRef::SF_Undefined) {
356 sym.def = LDPK_UNDEF;
357 if (GV && GV->hasExternalWeakLinkage())
Rafael Espindola56548522009-04-24 16:55:21 +0000358 sym.def = LDPK_WEAKUNDEF;
Rafael Espindola33466a72014-08-21 20:28:55 +0000359 } else {
360 sym.def = LDPK_DEF;
361 if (GV) {
362 assert(!GV->hasExternalWeakLinkage() &&
363 !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
364 if (GV->hasCommonLinkage())
365 sym.def = LDPK_COMMON;
366 else if (GV->isWeakForLinker())
367 sym.def = LDPK_WEAKDEF;
368 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000369 }
370
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000371 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000372 sym.comdat_key = nullptr;
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000373 if (GV) {
374 const GlobalObject *Base = getBaseObject(*GV);
375 if (!Base)
376 message(LDPL_FATAL, "Unable to determine comdat of alias!");
377 const Comdat *C = Base->getComdat();
378 if (C)
379 sym.comdat_key = strdup(C->getName().str().c_str());
380 else if (Base->hasWeakLinkage() || Base->hasLinkOnceLinkage())
381 sym.comdat_key = strdup(sym.name);
382 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000383
384 sym.resolution = LDPR_UNKNOWN;
385 }
386
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000387 if (!cf.syms.empty()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000388 if (add_symbols(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
389 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000390 return LDPS_ERR;
391 }
392 }
393
394 return LDPS_OK;
395}
396
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000397static void keepGlobalValue(GlobalValue &GV,
398 std::vector<GlobalAlias *> &KeptAliases) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000399 assert(!GV.hasLocalLinkage());
400
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000401 if (auto *GA = dyn_cast<GlobalAlias>(&GV))
402 KeptAliases.push_back(GA);
403
Rafael Espindola33466a72014-08-21 20:28:55 +0000404 switch (GV.getLinkage()) {
405 default:
406 break;
407 case GlobalValue::LinkOnceAnyLinkage:
408 GV.setLinkage(GlobalValue::WeakAnyLinkage);
409 break;
410 case GlobalValue::LinkOnceODRLinkage:
411 GV.setLinkage(GlobalValue::WeakODRLinkage);
412 break;
413 }
414
415 assert(!GV.isDiscardableIfUnused());
416}
417
Rafael Espindola33466a72014-08-21 20:28:55 +0000418static void internalize(GlobalValue &GV) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000419 if (GV.isDeclarationForLinker())
Rafael Espindola33466a72014-08-21 20:28:55 +0000420 return; // We get here if there is a matching asm definition.
421 if (!GV.hasLocalLinkage())
422 GV.setLinkage(GlobalValue::InternalLinkage);
423}
424
425static void drop(GlobalValue &GV) {
426 if (auto *F = dyn_cast<Function>(&GV)) {
427 F->deleteBody();
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000428 F->setComdat(nullptr); // Should deleteBody do this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000429 return;
430 }
431
432 if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
433 Var->setInitializer(nullptr);
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000434 Var->setLinkage(
435 GlobalValue::ExternalLinkage); // Should setInitializer do this?
436 Var->setComdat(nullptr); // and this?
Rafael Espindola33466a72014-08-21 20:28:55 +0000437 return;
438 }
439
440 auto &Alias = cast<GlobalAlias>(GV);
441 Module &M = *Alias.getParent();
442 PointerType &Ty = *cast<PointerType>(Alias.getType());
443 GlobalValue::LinkageTypes L = Alias.getLinkage();
444 auto *Var =
445 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false, L,
446 /*Initializer*/ nullptr);
447 Var->takeName(&Alias);
448 Alias.replaceAllUsesWith(Var);
Rafael Espindola71143ed2014-09-10 19:39:41 +0000449 Alias.eraseFromParent();
Rafael Espindola33466a72014-08-21 20:28:55 +0000450}
451
452static const char *getResolutionName(ld_plugin_symbol_resolution R) {
453 switch (R) {
454 case LDPR_UNKNOWN:
455 return "UNKNOWN";
456 case LDPR_UNDEF:
457 return "UNDEF";
458 case LDPR_PREVAILING_DEF:
459 return "PREVAILING_DEF";
460 case LDPR_PREVAILING_DEF_IRONLY:
461 return "PREVAILING_DEF_IRONLY";
462 case LDPR_PREEMPTED_REG:
463 return "PREEMPTED_REG";
464 case LDPR_PREEMPTED_IR:
465 return "PREEMPTED_IR";
466 case LDPR_RESOLVED_IR:
467 return "RESOLVED_IR";
468 case LDPR_RESOLVED_EXEC:
469 return "RESOLVED_EXEC";
470 case LDPR_RESOLVED_DYN:
471 return "RESOLVED_DYN";
472 case LDPR_PREVAILING_DEF_IRONLY_EXP:
473 return "PREVAILING_DEF_IRONLY_EXP";
474 }
Rafael Espindola2754dbb2014-10-10 00:48:13 +0000475 llvm_unreachable("Unknown resolution");
Rafael Espindola33466a72014-08-21 20:28:55 +0000476}
477
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000478static GlobalObject *makeInternalReplacement(GlobalObject *GO) {
479 Module *M = GO->getParent();
480 GlobalObject *Ret;
481 if (auto *F = dyn_cast<Function>(GO)) {
Rafael Espindola246c4fb2014-11-01 16:46:18 +0000482 if (F->materialize())
483 message(LDPL_FATAL, "LLVM gold plugin has failed to read a function");
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000484
Rafael Espindolacb695832014-10-07 03:19:55 +0000485 auto *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
486 F->getName(), M);
Rafael Espindola93aec712014-10-07 00:47:38 +0000487
488 ValueToValueMapTy VM;
489 Function::arg_iterator NewI = NewF->arg_begin();
490 for (auto &Arg : F->args()) {
491 NewI->setName(Arg.getName());
492 VM[&Arg] = NewI;
493 ++NewI;
494 }
495
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000496 NewF->getBasicBlockList().splice(NewF->end(), F->getBasicBlockList());
Rafael Espindola93aec712014-10-07 00:47:38 +0000497 for (auto &BB : *NewF) {
498 for (auto &Inst : BB)
499 RemapInstruction(&Inst, VM, RF_IgnoreMissingEntries);
500 }
501
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000502 Ret = NewF;
503 F->deleteBody();
504 } else {
505 auto *Var = cast<GlobalVariable>(GO);
506 Ret = new GlobalVariable(
507 *M, Var->getType()->getElementType(), Var->isConstant(),
Rafael Espindolacb695832014-10-07 03:19:55 +0000508 Var->getLinkage(), Var->getInitializer(), Var->getName(),
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000509 nullptr, Var->getThreadLocalMode(), Var->getType()->getAddressSpace(),
510 Var->isExternallyInitialized());
511 Var->setInitializer(nullptr);
512 }
513 Ret->copyAttributesFrom(GO);
Rafael Espindolacb695832014-10-07 03:19:55 +0000514 Ret->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000515 Ret->setComdat(GO->getComdat());
516
517 return Ret;
518}
519
520namespace {
521class LocalValueMaterializer : public ValueMaterializer {
522 DenseSet<GlobalValue *> &Dropped;
523
524public:
525 LocalValueMaterializer(DenseSet<GlobalValue *> &Dropped) : Dropped(Dropped) {}
526 Value *materializeValueFor(Value *V) override;
527};
528}
529
530Value *LocalValueMaterializer::materializeValueFor(Value *V) {
531 auto *GV = dyn_cast<GlobalValue>(V);
532 if (!GV)
533 return nullptr;
534 if (!Dropped.count(GV))
535 return nullptr;
536 assert(!isa<GlobalAlias>(GV) && "Found alias point to weak alias.");
537 return makeInternalReplacement(cast<GlobalObject>(GV));
538}
539
540static Constant *mapConstantToLocalCopy(Constant *C, ValueToValueMapTy &VM,
541 LocalValueMaterializer *Materializer) {
542 return MapValue(C, VM, RF_IgnoreMissingEntries, nullptr, Materializer);
543}
544
Rafael Espindola33466a72014-08-21 20:28:55 +0000545static std::unique_ptr<Module>
546getModuleForFile(LLVMContext &Context, claimed_file &F, raw_fd_ostream *ApiFile,
547 StringSet<> &Internalize, StringSet<> &Maybe) {
548 ld_plugin_input_file File;
549 if (get_input_file(F.handle, &File) != LDPS_OK)
550 message(LDPL_FATAL, "Failed to get file information");
551
552 if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
553 message(LDPL_FATAL, "Failed to get symbol information");
554
555 const void *View;
556 if (get_view(F.handle, &View) != LDPS_OK)
557 message(LDPL_FATAL, "Failed to get a view of file");
558
Peter Collingbourne10039c02014-09-18 21:28:49 +0000559 llvm::ErrorOr<MemoryBufferRef> MBOrErr =
560 object::IRObjectFile::findBitcodeInMemBuffer(
561 MemoryBufferRef(StringRef((const char *)View, File.filesize), ""));
562 if (std::error_code EC = MBOrErr.getError())
563 message(LDPL_FATAL, "Could not read bitcode from file : %s",
564 EC.message().c_str());
565
566 std::unique_ptr<MemoryBuffer> Buffer =
567 MemoryBuffer::getMemBuffer(MBOrErr->getBuffer(), "", false);
Rafael Espindola33466a72014-08-21 20:28:55 +0000568
569 if (release_input_file(F.handle) != LDPS_OK)
570 message(LDPL_FATAL, "Failed to release file information");
571
Rafael Espindola68812152014-09-03 17:31:46 +0000572 ErrorOr<Module *> MOrErr = getLazyBitcodeModule(std::move(Buffer), Context);
Rafael Espindola33466a72014-08-21 20:28:55 +0000573
574 if (std::error_code EC = MOrErr.getError())
575 message(LDPL_FATAL, "Could not read bitcode from file : %s",
576 EC.message().c_str());
Rafael Espindola33466a72014-08-21 20:28:55 +0000577
578 std::unique_ptr<Module> M(MOrErr.get());
579
580 SmallPtrSet<GlobalValue *, 8> Used;
581 collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
582
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000583 DenseSet<GlobalValue *> Drop;
584 std::vector<GlobalAlias *> KeptAliases;
Rafael Espindola33466a72014-08-21 20:28:55 +0000585 for (ld_plugin_symbol &Sym : F.syms) {
586 ld_plugin_symbol_resolution Resolution =
587 (ld_plugin_symbol_resolution)Sym.resolution;
588
589 if (options::generate_api_file)
590 *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
591
592 GlobalValue *GV = M->getNamedValue(Sym.name);
593 if (!GV)
594 continue; // Asm symbol.
595
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000596 if (Resolution != LDPR_PREVAILING_DEF_IRONLY && GV->hasCommonLinkage()) {
Rafael Espindola890db272014-09-09 20:08:22 +0000597 // Common linkage is special. There is no single symbol that wins the
598 // resolution. Instead we have to collect the maximum alignment and size.
599 // The IR linker does that for us if we just pass it every common GV.
Rafael Espindola51bd8ee2014-09-17 20:41:13 +0000600 // We still have to keep track of LDPR_PREVAILING_DEF_IRONLY so we
601 // internalize once the IR linker has done its job.
Rafael Espindola890db272014-09-09 20:08:22 +0000602 continue;
603 }
604
Rafael Espindola33466a72014-08-21 20:28:55 +0000605 switch (Resolution) {
606 case LDPR_UNKNOWN:
607 llvm_unreachable("Unexpected resolution");
608
609 case LDPR_RESOLVED_IR:
610 case LDPR_RESOLVED_EXEC:
611 case LDPR_RESOLVED_DYN:
612 case LDPR_UNDEF:
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000613 assert(GV->isDeclarationForLinker());
Rafael Espindola33466a72014-08-21 20:28:55 +0000614 break;
615
616 case LDPR_PREVAILING_DEF_IRONLY: {
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000617 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000618 if (!Used.count(GV)) {
619 // Since we use the regular lib/Linker, we cannot just internalize GV
620 // now or it will not be copied to the merged module. Instead we force
621 // it to be copied and then internalize it.
Rafael Espindola33466a72014-08-21 20:28:55 +0000622 Internalize.insert(Sym.name);
623 }
624 break;
625 }
626
627 case LDPR_PREVAILING_DEF:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000628 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000629 break;
630
Rafael Espindola33466a72014-08-21 20:28:55 +0000631 case LDPR_PREEMPTED_IR:
Rafael Espindoladfc7ed72014-10-07 04:06:13 +0000632 // Gold might have selected a linkonce_odr and preempted a weak_odr.
633 // In that case we have to make sure we don't end up internalizing it.
634 if (!GV->isDiscardableIfUnused())
635 Maybe.erase(Sym.name);
636
637 // fall-through
638 case LDPR_PREEMPTED_REG:
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000639 Drop.insert(GV);
Rafael Espindola33466a72014-08-21 20:28:55 +0000640 break;
641
642 case LDPR_PREVAILING_DEF_IRONLY_EXP: {
643 // We can only check for address uses after we merge the modules. The
644 // reason is that this GV might have a copy in another module
645 // and in that module the address might be significant, but that
646 // copy will be LDPR_PREEMPTED_IR.
647 if (GV->hasLinkOnceODRLinkage())
648 Maybe.insert(Sym.name);
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000649 keepGlobalValue(*GV, KeptAliases);
Rafael Espindola33466a72014-08-21 20:28:55 +0000650 break;
651 }
652 }
653
654 free(Sym.name);
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000655 free(Sym.comdat_key);
Rafael Espindola33466a72014-08-21 20:28:55 +0000656 Sym.name = nullptr;
657 Sym.comdat_key = nullptr;
658 }
659
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000660 ValueToValueMapTy VM;
661 LocalValueMaterializer Materializer(Drop);
662 for (GlobalAlias *GA : KeptAliases) {
663 // Gold told us to keep GA. It is possible that a GV usied in the aliasee
664 // expression is being dropped. If that is the case, that GV must be copied.
665 Constant *Aliasee = GA->getAliasee();
666 Constant *Replacement = mapConstantToLocalCopy(Aliasee, VM, &Materializer);
667 if (Aliasee != Replacement)
668 GA->setAliasee(Replacement);
Rafael Espindola33466a72014-08-21 20:28:55 +0000669 }
670
Rafael Espindolaf7ecb112014-08-22 23:26:10 +0000671 for (auto *GV : Drop)
672 drop(*GV);
673
Rafael Espindola33466a72014-08-21 20:28:55 +0000674 return M;
675}
676
677static void runLTOPasses(Module &M, TargetMachine &TM) {
678 PassManager passes;
679 PassManagerBuilder PMB;
680 PMB.LibraryInfo = new TargetLibraryInfo(Triple(TM.getTargetTriple()));
681 PMB.Inliner = createFunctionInliningPass();
682 PMB.VerifyInput = true;
683 PMB.VerifyOutput = true;
Rafael Espindola8391dbd2014-10-30 00:11:24 +0000684 PMB.LoopVectorize = true;
Rafael Espindola919fb532014-10-30 00:38:54 +0000685 PMB.SLPVectorize = true;
Rafael Espindola33466a72014-08-21 20:28:55 +0000686 PMB.populateLTOPassManager(passes, &TM);
687 passes.run(M);
688}
689
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000690static void saveBCFile(StringRef Path, Module &M) {
691 std::error_code EC;
692 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
693 if (EC)
694 message(LDPL_FATAL, "Failed to write the output file.");
695 WriteBitcodeToFile(&M, OS);
696}
697
Rafael Espindola33466a72014-08-21 20:28:55 +0000698static void codegen(Module &M) {
699 const std::string &TripleStr = M.getTargetTriple();
700 Triple TheTriple(TripleStr);
701
702 std::string ErrMsg;
703 const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
704 if (!TheTarget)
705 message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
706
707 if (unsigned NumOpts = options::extra.size())
708 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
709
710 SubtargetFeatures Features;
711 Features.getDefaultSubtargetFeatures(TheTriple);
712 for (const std::string &A : MAttrs)
713 Features.AddFeature(A);
714
715 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
716 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
717 TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
718 CodeModel::Default, CodeGenOpt::Aggressive));
719
720 runLTOPasses(M, *TM);
721
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000722 if (options::TheOutputType == options::OT_SAVE_TEMPS)
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000723 saveBCFile(output_name + ".opt.bc", M);
724
Rafael Espindola33466a72014-08-21 20:28:55 +0000725 PassManager CodeGenPasses;
Rafael Espindolac435adc2014-09-10 21:27:43 +0000726 CodeGenPasses.add(new DataLayoutPass());
Rafael Espindola33466a72014-08-21 20:28:55 +0000727
728 SmallString<128> Filename;
729 int FD;
730 if (options::obj_path.empty()) {
731 std::error_code EC =
732 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
733 if (EC)
Duncan P. N. Exon Smithf6ab4702014-11-19 22:39:21 +0000734 message(LDPL_FATAL, "Could not create temporary file: %s",
Rafael Espindola33466a72014-08-21 20:28:55 +0000735 EC.message().c_str());
736 } else {
737 Filename = options::obj_path;
738 std::error_code EC =
739 sys::fs::openFileForWrite(Filename.c_str(), FD, sys::fs::F_None);
740 if (EC)
741 message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
742 }
743
744 {
745 raw_fd_ostream OS(FD, true);
746 formatted_raw_ostream FOS(OS);
747
748 if (TM->addPassesToEmitFile(CodeGenPasses, FOS,
749 TargetMachine::CGFT_ObjectFile))
750 message(LDPL_FATAL, "Failed to setup codegen");
751 CodeGenPasses.run(M);
752 }
753
754 if (add_input_file(Filename.c_str()) != LDPS_OK)
755 message(LDPL_FATAL,
756 "Unable to add .o file to the link. File left behind in: %s",
757 Filename.c_str());
758
759 if (options::obj_path.empty())
760 Cleanup.push_back(Filename.c_str());
Rafael Espindola282a4702013-10-31 20:51:58 +0000761}
762
Rafael Espindolab6393292014-07-30 01:23:45 +0000763/// gold informs us that all symbols have been read. At this point, we use
764/// get_symbols to see if any of our definitions have been overridden by a
765/// native object file. Then, perform optimization and codegen.
Rafael Espindola33466a72014-08-21 20:28:55 +0000766static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
767 if (Modules.empty())
768 return LDPS_OK;
Rafael Espindola9ef90d52011-02-20 18:28:29 +0000769
Rafael Espindola33466a72014-08-21 20:28:55 +0000770 LLVMContext Context;
771 std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
772 Linker L(Combined.get());
773
774 std::string DefaultTriple = sys::getDefaultTargetTriple();
775
776 StringSet<> Internalize;
777 StringSet<> Maybe;
Rafael Espindolad2aac572014-07-30 01:52:40 +0000778 for (claimed_file &F : Modules) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000779 std::unique_ptr<Module> M =
780 getModuleForFile(Context, F, ApiFile, Internalize, Maybe);
781 if (!options::triple.empty())
782 M->setTargetTriple(options::triple.c_str());
783 else if (M->getTargetTriple().empty()) {
784 M->setTargetTriple(DefaultTriple);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000785 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000786
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000787 if (L.linkInModule(M.get()))
788 message(LDPL_FATAL, "Failed to link module");
Rafael Espindola77b6d012010-06-14 21:20:52 +0000789 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000790
Rafael Espindola33466a72014-08-21 20:28:55 +0000791 for (const auto &Name : Internalize) {
792 GlobalValue *GV = Combined->getNamedValue(Name.first());
793 if (GV)
794 internalize(*GV);
795 }
796
797 for (const auto &Name : Maybe) {
798 GlobalValue *GV = Combined->getNamedValue(Name.first());
799 if (!GV)
800 continue;
801 GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
802 if (canBeOmittedFromSymbolTable(GV))
803 internalize(*GV);
804 }
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000805
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000806 if (options::TheOutputType == options::OT_DISABLE)
807 return LDPS_OK;
808
809 if (options::TheOutputType != options::OT_NORMAL) {
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000810 std::string path;
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000811 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000812 path = output_name;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000813 else
814 path = output_name + ".bc";
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000815 saveBCFile(path, *L.getModule());
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000816 if (options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola55b32542014-08-11 19:06:54 +0000817 return LDPS_OK;
Rafael Espindolaba3398b2010-05-13 13:39:31 +0000818 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +0000819
Rafael Espindola33466a72014-08-21 20:28:55 +0000820 codegen(*L.getModule());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000821
Rafael Espindolaef498152010-06-23 20:20:59 +0000822 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +0000823 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
824 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +0000825
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000826 return LDPS_OK;
827}
828
Rafael Espindola55b32542014-08-11 19:06:54 +0000829static ld_plugin_status all_symbols_read_hook(void) {
830 ld_plugin_status Ret;
831 if (!options::generate_api_file) {
832 Ret = allSymbolsReadHook(nullptr);
833 } else {
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000834 std::error_code EC;
835 raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
836 if (EC)
Rafael Espindola55b32542014-08-11 19:06:54 +0000837 message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000838 EC.message().c_str());
Rafael Espindola33466a72014-08-21 20:28:55 +0000839 Ret = allSymbolsReadHook(&ApiFile);
Rafael Espindola55b32542014-08-11 19:06:54 +0000840 }
841
Rafael Espindola947bdb62014-11-25 20:52:49 +0000842 llvm_shutdown();
843
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000844 if (options::TheOutputType == options::OT_BC_ONLY ||
845 options::TheOutputType == options::OT_DISABLE)
Rafael Espindola55b32542014-08-11 19:06:54 +0000846 exit(0);
847
848 return Ret;
849}
850
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000851static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +0000852 for (std::string &Name : Cleanup) {
853 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000854 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +0000855 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000856 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +0000857 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000858
859 return LDPS_OK;
860}