1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 .
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Config/config.h"
16 #include "plugin-api.h"
18 #include "llvm-c/lto.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/System/Errno.h"
22 #include "llvm/System/Path.h"
23 #include "llvm/System/Program.h"
35 ld_plugin_status discard_message(int level, const char *format, ...) {
36 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
37 // callback in the transfer vector. This should never be called.
41 ld_plugin_add_symbols add_symbols = NULL;
42 ld_plugin_get_symbols get_symbols = NULL;
43 ld_plugin_add_input_file add_input_file = NULL;
44 ld_plugin_message message = discard_message;
52 std::vector<ld_plugin_symbol> syms;
55 lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
56 std::list<claimed_file> Modules;
57 std::vector<sys::Path> Cleanup;
61 static bool generate_api_file = false;
62 static std::string bc_path;
63 static const char *as_path = NULL;
64 // Additional options to pass into the code generator.
65 // Note: This array will contain all plugin options which are not claimed
66 // as plugin exclusive to pass to the code generator.
67 // For example, "generate-api-file" and "as"options are for the plugin
68 // use only and will not be passed.
69 static std::vector<std::string> extra;
71 static void process_plugin_option(const char* opt)
76 if (strcmp("generate-api-file", opt) == 0) {
77 generate_api_file = true;
78 } else if (strncmp("as=", opt, 3) == 0) {
80 (*message)(LDPL_WARNING, "Path to as specified twice. "
81 "Discarding %s", opt);
83 as_path = strdup(opt + 3);
85 } else if(llvm::StringRef(opt).startswith("also-emit-llvm=")) {
86 const char *path = opt + strlen("also-emit-llvm=");
88 (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
89 "Discarding %s", opt);
94 // Save this option to pass to the code generator.
95 extra.push_back(std::string(opt));
100 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
102 static ld_plugin_status all_symbols_read_hook(void);
103 static ld_plugin_status cleanup_hook(void);
105 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
106 ld_plugin_status onload(ld_plugin_tv *tv) {
107 // We're given a pointer to the first transfer vector. We read through them
108 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
109 // contain pointers to functions that we need to call to register our own
110 // hooks. The others are addresses of functions we can use to call into gold
113 bool registeredClaimFile = false;
114 bool registeredAllSymbolsRead = false;
115 bool registeredCleanup = false;
117 for (; tv->tv_tag != LDPT_NULL; ++tv) {
118 switch (tv->tv_tag) {
119 case LDPT_API_VERSION:
120 api_version = tv->tv_u.tv_val;
122 case LDPT_GOLD_VERSION: // major * 100 + minor
123 gold_version = tv->tv_u.tv_val;
125 case LDPT_LINKER_OUTPUT:
126 switch (tv->tv_u.tv_val) {
128 case LDPO_DYN: // .so
129 output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
131 case LDPO_EXEC: // .exe
132 output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
135 (*message)(LDPL_ERROR, "Unknown output file type %d",
139 // TODO: add an option to disable PIC.
140 //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
143 options::process_plugin_option(tv->tv_u.tv_string);
145 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
146 ld_plugin_register_claim_file callback;
147 callback = tv->tv_u.tv_register_claim_file;
149 if ((*callback)(claim_file_hook) != LDPS_OK)
152 registeredClaimFile = true;
154 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
155 ld_plugin_register_all_symbols_read callback;
156 callback = tv->tv_u.tv_register_all_symbols_read;
158 if ((*callback)(all_symbols_read_hook) != LDPS_OK)
161 registeredAllSymbolsRead = true;
163 case LDPT_REGISTER_CLEANUP_HOOK: {
164 ld_plugin_register_cleanup callback;
165 callback = tv->tv_u.tv_register_cleanup;
167 if ((*callback)(cleanup_hook) != LDPS_OK)
170 registeredCleanup = true;
172 case LDPT_ADD_SYMBOLS:
173 add_symbols = tv->tv_u.tv_add_symbols;
175 case LDPT_GET_SYMBOLS:
176 get_symbols = tv->tv_u.tv_get_symbols;
178 case LDPT_ADD_INPUT_FILE:
179 add_input_file = tv->tv_u.tv_add_input_file;
182 message = tv->tv_u.tv_message;
189 if (!registeredClaimFile) {
190 (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
194 (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
201 /// claim_file_hook - called by gold to see whether this file is one that
202 /// our plugin can handle. We'll try to open it and register all the symbols
203 /// with add_symbol if possible.
204 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
208 // Gold has found what might be IR part-way inside of a file, such as
210 if (lseek(file->fd, file->offset, SEEK_SET) == -1) {
211 (*message)(LDPL_ERROR,
212 "Failed to seek to archive member of %s at offset %d: %s\n",
214 file->offset, sys::StrError(errno).c_str());
217 buf = malloc(file->filesize);
219 (*message)(LDPL_ERROR,
220 "Failed to allocate buffer for archive member of size: %d\n",
224 if (read(file->fd, buf, file->filesize) != file->filesize) {
225 (*message)(LDPL_ERROR,
226 "Failed to read archive member of %s at offset %d: %s\n",
229 sys::StrError(errno).c_str());
233 if (!lto_module_is_object_file_in_memory(buf, file->filesize)) {
237 } else if (!lto_module_is_object_file(file->name))
241 Modules.resize(Modules.size() + 1);
242 claimed_file &cf = Modules.back();
244 cf.M = buf ? lto_module_create_from_memory(buf, file->filesize) :
245 lto_module_create(file->name);
248 (*message)(LDPL_ERROR, "Failed to create LLVM module: %s",
249 lto_get_error_message());
252 cf.handle = file->handle;
253 unsigned sym_count = lto_module_get_num_symbols(cf.M);
254 cf.syms.reserve(sym_count);
256 for (unsigned i = 0; i != sym_count; ++i) {
257 lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i);
258 if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
261 cf.syms.push_back(ld_plugin_symbol());
262 ld_plugin_symbol &sym = cf.syms.back();
263 sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i));
266 int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
268 case LTO_SYMBOL_SCOPE_HIDDEN:
269 sym.visibility = LDPV_HIDDEN;
271 case LTO_SYMBOL_SCOPE_PROTECTED:
272 sym.visibility = LDPV_PROTECTED;
275 case LTO_SYMBOL_SCOPE_DEFAULT:
276 sym.visibility = LDPV_DEFAULT;
279 (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
283 int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
284 switch (definition) {
285 case LTO_SYMBOL_DEFINITION_REGULAR:
288 case LTO_SYMBOL_DEFINITION_UNDEFINED:
289 sym.def = LDPK_UNDEF;
291 case LTO_SYMBOL_DEFINITION_TENTATIVE:
292 sym.def = LDPK_COMMON;
294 case LTO_SYMBOL_DEFINITION_WEAK:
295 sym.def = LDPK_WEAKDEF;
297 case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
298 sym.def = LDPK_WEAKUNDEF;
301 (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
305 // LLVM never emits COMDAT.
307 sym.comdat_key = NULL;
309 sym.resolution = LDPR_UNKNOWN;
312 cf.syms.reserve(cf.syms.size());
314 if (!cf.syms.empty()) {
315 if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
316 (*message)(LDPL_ERROR, "Unable to add symbols!");
324 /// all_symbols_read_hook - gold informs us that all symbols have been read.
325 /// At this point, we use get_symbols to see if any of our definitions have
326 /// been overridden by a native object file. Then, perform optimization and
328 static ld_plugin_status all_symbols_read_hook(void) {
329 lto_code_gen_t cg = lto_codegen_create();
331 for (std::list<claimed_file>::iterator I = Modules.begin(),
332 E = Modules.end(); I != E; ++I)
333 lto_codegen_add_module(cg, I->M);
335 std::ofstream api_file;
336 if (options::generate_api_file) {
337 api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc);
338 if (!api_file.is_open()) {
339 (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing.");
344 // If we don't preserve any symbols, libLTO will assume that all symbols are
345 // needed. Keep all symbols unless we're producing a final executable.
346 if (output_type == LTO_CODEGEN_PIC_MODEL_STATIC) {
347 bool anySymbolsPreserved = false;
348 for (std::list<claimed_file>::iterator I = Modules.begin(),
349 E = Modules.end(); I != E; ++I) {
350 (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
351 for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
352 if (I->syms[i].resolution == LDPR_PREVAILING_DEF) {
353 lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name);
354 anySymbolsPreserved = true;
356 if (options::generate_api_file)
357 api_file << I->syms[i].name << "\n";
362 if (options::generate_api_file)
365 if (!anySymbolsPreserved) {
366 // This entire file is unnecessary!
367 lto_codegen_dispose(cg);
372 lto_codegen_set_pic_model(cg, output_type);
373 lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF);
374 if (options::as_path) {
375 sys::Path p = sys::Program::FindProgramByName(options::as_path);
376 lto_codegen_set_assembler_path(cg, p.c_str());
378 // Pass through extra options to the code generator.
379 if (!options::extra.empty()) {
380 for (std::vector<std::string>::iterator it = options::extra.begin();
381 it != options::extra.end(); ++it) {
382 lto_codegen_debug_options(cg, (*it).c_str());
386 if (options::bc_path != "") {
387 bool err = lto_codegen_write_merged_modules(cg, options::bc_path.c_str());
389 (*message)(LDPL_FATAL, "Failed to write the output file.");
392 const char *buffer = static_cast<const char *>(lto_codegen_compile(cg,
397 sys::Path uniqueObjPath("/tmp/llvmgold.o");
398 if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) {
399 (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
402 raw_fd_ostream *objFile =
403 new raw_fd_ostream(uniqueObjPath.c_str(), ErrMsg,
404 raw_fd_ostream::F_Binary);
405 if (!ErrMsg.empty()) {
407 (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
411 objFile->write(buffer, bufsize);
414 lto_codegen_dispose(cg);
416 if ((*add_input_file)(const_cast<char*>(uniqueObjPath.c_str())) != LDPS_OK) {
417 (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
418 (*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str());
422 Cleanup.push_back(uniqueObjPath);
427 static ld_plugin_status cleanup_hook(void) {
430 for (int i = 0, e = Cleanup.size(); i != e; ++i)
431 if (Cleanup[i].eraseFromDisk(false, &ErrMsg))
432 (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),