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" // plugin-api.h requires HAVE_STDINT_H
16 #include "llvm-c/lto.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/LTO/LTOCodeGenerator.h"
20 #include "llvm/LTO/LTOModule.h"
21 #include "llvm/Support/Errno.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/Program.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/ToolOutputFile.h"
32 #include <plugin-api.h>
33 #include <system_error>
37 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
38 // Precise and Debian Wheezy (binutils 2.23 is required)
47 std::vector<ld_plugin_symbol> syms;
51 static ld_plugin_status discard_message(int level, const char *format, ...) {
52 // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
53 // callback in the transfer vector. This should never be called.
57 static ld_plugin_add_symbols add_symbols = NULL;
58 static ld_plugin_get_symbols get_symbols = NULL;
59 static ld_plugin_add_input_file add_input_file = NULL;
60 static ld_plugin_set_extra_library_path set_extra_library_path = NULL;
61 static ld_plugin_get_view get_view = NULL;
62 static ld_plugin_message message = discard_message;
63 static lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
64 static std::string output_name = "";
65 static std::list<claimed_file> Modules;
66 static std::vector<std::string> Cleanup;
67 static LTOCodeGenerator *CodeGen = nullptr;
68 static StringSet<> CannotBeHidden;
69 static llvm::TargetOptions TargetOpts;
72 enum generate_bc { BC_NO, BC_ALSO, BC_ONLY };
73 static bool generate_api_file = false;
74 static generate_bc generate_bc_file = BC_NO;
75 static std::string bc_path;
76 static std::string obj_path;
77 static std::string extra_library_path;
78 static std::string triple;
79 static std::string mcpu;
80 // Additional options to pass into the code generator.
81 // Note: This array will contain all plugin options which are not claimed
82 // as plugin exclusive to pass to the code generator.
83 // For example, "generate-api-file" and "as"options are for the plugin
84 // use only and will not be passed.
85 static std::vector<const char *> extra;
87 static void process_plugin_option(const char* opt_)
91 llvm::StringRef opt = opt_;
93 if (opt == "generate-api-file") {
94 generate_api_file = true;
95 } else if (opt.startswith("mcpu=")) {
96 mcpu = opt.substr(strlen("mcpu="));
97 } else if (opt.startswith("extra-library-path=")) {
98 extra_library_path = opt.substr(strlen("extra_library_path="));
99 } else if (opt.startswith("mtriple=")) {
100 triple = opt.substr(strlen("mtriple="));
101 } else if (opt.startswith("obj-path=")) {
102 obj_path = opt.substr(strlen("obj-path="));
103 } else if (opt == "emit-llvm") {
104 generate_bc_file = BC_ONLY;
105 } else if (opt == "also-emit-llvm") {
106 generate_bc_file = BC_ALSO;
107 } else if (opt.startswith("also-emit-llvm=")) {
108 llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
109 generate_bc_file = BC_ALSO;
110 if (!bc_path.empty()) {
111 (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
112 "Discarding %s", opt_);
117 // Save this option to pass to the code generator.
118 extra.push_back(opt_);
123 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
125 static ld_plugin_status all_symbols_read_hook(void);
126 static ld_plugin_status cleanup_hook(void);
128 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
129 ld_plugin_status onload(ld_plugin_tv *tv) {
130 InitializeAllTargetInfos();
131 InitializeAllTargets();
132 InitializeAllTargetMCs();
133 InitializeAllAsmParsers();
134 InitializeAllAsmPrinters();
136 // We're given a pointer to the first transfer vector. We read through them
137 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
138 // contain pointers to functions that we need to call to register our own
139 // hooks. The others are addresses of functions we can use to call into gold
142 bool registeredClaimFile = false;
143 bool RegisteredAllSymbolsRead = false;
145 for (; tv->tv_tag != LDPT_NULL; ++tv) {
146 switch (tv->tv_tag) {
147 case LDPT_OUTPUT_NAME:
148 output_name = tv->tv_u.tv_string;
150 case LDPT_LINKER_OUTPUT:
151 switch (tv->tv_u.tv_val) {
153 case LDPO_DYN: // .so
154 case LDPO_PIE: // position independent executable
155 output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
157 case LDPO_EXEC: // .exe
158 output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
161 (*message)(LDPL_ERROR, "Unknown output file type %d",
167 options::process_plugin_option(tv->tv_u.tv_string);
169 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
170 ld_plugin_register_claim_file callback;
171 callback = tv->tv_u.tv_register_claim_file;
173 if ((*callback)(claim_file_hook) != LDPS_OK)
176 registeredClaimFile = true;
178 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
179 ld_plugin_register_all_symbols_read callback;
180 callback = tv->tv_u.tv_register_all_symbols_read;
182 if ((*callback)(all_symbols_read_hook) != LDPS_OK)
185 RegisteredAllSymbolsRead = true;
187 case LDPT_REGISTER_CLEANUP_HOOK: {
188 ld_plugin_register_cleanup callback;
189 callback = tv->tv_u.tv_register_cleanup;
191 if ((*callback)(cleanup_hook) != LDPS_OK)
194 case LDPT_ADD_SYMBOLS:
195 add_symbols = tv->tv_u.tv_add_symbols;
197 case LDPT_GET_SYMBOLS_V2:
198 get_symbols = tv->tv_u.tv_get_symbols;
200 case LDPT_ADD_INPUT_FILE:
201 add_input_file = tv->tv_u.tv_add_input_file;
203 case LDPT_SET_EXTRA_LIBRARY_PATH:
204 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
207 get_view = tv->tv_u.tv_get_view;
210 message = tv->tv_u.tv_message;
217 if (!registeredClaimFile) {
218 (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
222 (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
226 if (!RegisteredAllSymbolsRead)
229 CodeGen = new LTOCodeGenerator();
231 // Pass through extra options to the code generator.
232 if (!options::extra.empty()) {
233 for (const char *Opt : options::extra)
234 CodeGen->setCodeGenDebugOptions(Opt);
237 CodeGen->parseCodeGenDebugOptions();
240 for (unsigned I = 0; I < MAttrs.size(); ++I) {
243 Attrs.append(MAttrs[I]);
245 CodeGen->setAttr(Attrs.c_str());
248 TargetOpts = InitTargetOptionsFromCodeGenFlags();
249 CodeGen->setTargetOptions(TargetOpts);
254 /// Called by gold to see whether this file is one that our plugin can handle.
255 /// We'll try to open it and register all the symbols with add_symbol if
257 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
260 std::unique_ptr<MemoryBuffer> buffer;
262 if (get_view(file->handle, &view) != LDPS_OK) {
263 (*message)(LDPL_ERROR, "Failed to get a view of %s", file->name);
268 // Gold has found what might be IR part-way inside of a file, such as
271 offset = file->offset;
273 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
274 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
276 if (std::error_code EC = BufferOrErr.getError()) {
277 (*message)(LDPL_ERROR, EC.message().c_str());
280 buffer = std::move(BufferOrErr.get());
281 view = buffer->getBufferStart();
284 if (!LTOModule::isBitcodeFile(view, file->filesize))
291 LTOModule::createFromBuffer(view, file->filesize, TargetOpts, Error);
293 (*message)(LDPL_ERROR,
294 "LLVM gold plugin has failed to create LTO module: %s",
299 Modules.resize(Modules.size() + 1);
300 claimed_file &cf = Modules.back();
302 if (!options::triple.empty())
303 M->setTargetTriple(options::triple.c_str());
305 cf.handle = file->handle;
306 unsigned sym_count = M->getSymbolCount();
307 cf.syms.reserve(sym_count);
309 for (unsigned i = 0; i != sym_count; ++i) {
310 lto_symbol_attributes attrs = M->getSymbolAttributes(i);
311 if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
314 cf.syms.push_back(ld_plugin_symbol());
315 ld_plugin_symbol &sym = cf.syms.back();
316 sym.name = strdup(M->getSymbolName(i));
319 int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
320 bool CanBeHidden = scope == LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
322 CannotBeHidden.insert(sym.name);
324 case LTO_SYMBOL_SCOPE_HIDDEN:
325 sym.visibility = LDPV_HIDDEN;
327 case LTO_SYMBOL_SCOPE_PROTECTED:
328 sym.visibility = LDPV_PROTECTED;
331 case LTO_SYMBOL_SCOPE_DEFAULT:
332 case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN:
333 sym.visibility = LDPV_DEFAULT;
336 (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
340 int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
341 sym.comdat_key = NULL;
342 switch (definition) {
343 case LTO_SYMBOL_DEFINITION_REGULAR:
346 case LTO_SYMBOL_DEFINITION_UNDEFINED:
347 sym.def = LDPK_UNDEF;
349 case LTO_SYMBOL_DEFINITION_TENTATIVE:
350 sym.def = LDPK_COMMON;
352 case LTO_SYMBOL_DEFINITION_WEAK:
353 sym.comdat_key = sym.name;
354 sym.def = LDPK_WEAKDEF;
356 case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
357 sym.def = LDPK_WEAKUNDEF;
360 (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
366 sym.resolution = LDPR_UNKNOWN;
369 cf.syms.reserve(cf.syms.size());
371 if (!cf.syms.empty()) {
372 if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
373 (*message)(LDPL_ERROR, "Unable to add symbols!");
380 if (!CodeGen->addModule(M, Error)) {
381 (*message)(LDPL_ERROR, "Error linking module: %s", Error.c_str());
391 static bool mustPreserve(const claimed_file &F, int i) {
392 if (F.syms[i].resolution == LDPR_PREVAILING_DEF)
394 if (F.syms[i].resolution == LDPR_PREVAILING_DEF_IRONLY_EXP)
395 return CannotBeHidden.count(F.syms[i].name);
399 /// all_symbols_read_hook - gold informs us that all symbols have been read.
400 /// At this point, we use get_symbols to see if any of our definitions have
401 /// been overridden by a native object file. Then, perform optimization and
403 static ld_plugin_status all_symbols_read_hook(void) {
404 // FIXME: raw_fd_ostream should be able to represent an unopened file.
405 std::unique_ptr<raw_fd_ostream> api_file;
409 if (options::generate_api_file) {
411 api_file.reset(new raw_fd_ostream("apifile.txt", Error, sys::fs::F_None));
413 (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
417 for (std::list<claimed_file>::iterator I = Modules.begin(),
418 E = Modules.end(); I != E; ++I) {
421 (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
422 for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
423 if (mustPreserve(*I, i)) {
424 CodeGen->addMustPreserveSymbol(I->syms[i].name);
426 if (options::generate_api_file)
427 (*api_file) << I->syms[i].name << "\n";
432 CodeGen->setCodePICModel(output_type);
433 CodeGen->setDebugInfo(LTO_DEBUG_MODEL_DWARF);
434 if (!options::mcpu.empty())
435 CodeGen->setCpu(options::mcpu.c_str());
437 if (options::generate_bc_file != options::BC_NO) {
439 if (options::generate_bc_file == options::BC_ONLY)
441 else if (!options::bc_path.empty())
442 path = options::bc_path;
444 path = output_name + ".bc";
446 if (!CodeGen->writeMergedModules(path.c_str(), Error))
447 (*message)(LDPL_FATAL, "Failed to write the output file.");
448 if (options::generate_bc_file == options::BC_ONLY) {
458 if (!CodeGen->compile_to_file(&Temp, /*DisableOpt*/ false, /*DisableInline*/
459 false, /*DisableGVNLoadPRE*/ false, Error))
460 (*message)(LDPL_ERROR, "Could not produce a combined object file\n");
465 for (std::list<claimed_file>::iterator I = Modules.begin(),
466 E = Modules.end(); I != E; ++I) {
467 for (unsigned i = 0; i != I->syms.size(); ++i) {
468 ld_plugin_symbol &sym = I->syms[i];
473 if ((*add_input_file)(ObjPath.c_str()) != LDPS_OK) {
474 (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
475 (*message)(LDPL_ERROR, "File left behind in: %s", ObjPath.c_str());
479 if (!options::extra_library_path.empty() &&
480 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
481 (*message)(LDPL_ERROR, "Unable to set the extra library path.");
485 if (options::obj_path.empty())
486 Cleanup.push_back(ObjPath);
491 static ld_plugin_status cleanup_hook(void) {
492 for (int i = 0, e = Cleanup.size(); i != e; ++i) {
493 std::error_code EC = sys::fs::remove(Cleanup[i]);
495 (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
496 EC.message().c_str());