13bc64e83547865f5050a8aadf2aac41db927315
[oota-llvm.git] / tools / gold / gold-plugin.cpp
1 //===-- 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
15 #include "llvm/Config/config.h"
16 #include "plugin-api.h"
17
18 #include "llvm-c/lto.h"
19
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"
24
25 #include <cerrno>
26 #include <cstdlib>
27 #include <cstring>
28 #include <fstream>
29 #include <list>
30 #include <vector>
31
32 using namespace llvm;
33
34 namespace {
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.
38     abort();
39   }
40
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_add_input_library add_input_library = NULL;
45   ld_plugin_set_extra_library_path set_extra_library_path = NULL;
46   ld_plugin_message message = discard_message;
47
48   int api_version = 0;
49   int gold_version = 0;
50
51   struct claimed_file {
52     lto_module_t M;
53     void *handle;
54     std::vector<ld_plugin_symbol> syms;
55   };
56
57   lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
58   std::string output_name = "";
59   std::list<claimed_file> Modules;
60   std::vector<sys::Path> Cleanup;
61 }
62
63 namespace options {
64   enum generate_bc { BC_NO, BC_ALSO, BC_ONLY };
65   static bool generate_api_file = false;
66   static generate_bc generate_bc_file = BC_NO;
67   static std::string bc_path;
68   static std::string as_path;
69   static std::vector<std::string> pass_through;
70   static std::string extra_library_path;
71   // Additional options to pass into the code generator.
72   // Note: This array will contain all plugin options which are not claimed
73   // as plugin exclusive to pass to the code generator.
74   // For example, "generate-api-file" and "as"options are for the plugin
75   // use only and will not be passed.
76   static std::vector<std::string> extra;
77
78   static void process_plugin_option(const char* opt_)
79   {
80     if (opt_ == NULL)
81       return;
82     llvm::StringRef opt = opt_;
83
84     if (opt == "generate-api-file") {
85       generate_api_file = true;
86     } else if (opt.startswith("as=")) {
87       if (!as_path.empty()) {
88         (*message)(LDPL_WARNING, "Path to as specified twice. "
89                    "Discarding %s", opt_);
90       } else {
91         as_path = opt.substr(strlen("as="));
92       }
93     } else if (opt.startswith("extra-library-path=")) {
94       extra_library_path = opt.substr(strlen("extra_library_path="));
95     } else if (opt.startswith("pass-through=")) {
96       llvm::StringRef item = opt.substr(strlen("pass-through="));
97       pass_through.push_back(item.str());
98     } else if (opt == "emit-llvm") {
99       generate_bc_file = BC_ONLY;
100     } else if (opt == "also-emit-llvm") {
101       generate_bc_file = BC_ALSO;
102     } else if (opt.startswith("also-emit-llvm=")) {
103       llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
104       generate_bc_file = BC_ALSO;
105       if (!bc_path.empty()) {
106         (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
107                    "Discarding %s", opt_);
108       } else {
109         bc_path = path;
110       }
111     } else {
112       // Save this option to pass to the code generator.
113       extra.push_back(opt);
114     }
115   }
116 }
117
118 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
119                                         int *claimed);
120 static ld_plugin_status all_symbols_read_hook(void);
121 static ld_plugin_status cleanup_hook(void);
122
123 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
124 ld_plugin_status onload(ld_plugin_tv *tv) {
125   // We're given a pointer to the first transfer vector. We read through them
126   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
127   // contain pointers to functions that we need to call to register our own
128   // hooks. The others are addresses of functions we can use to call into gold
129   // for services.
130
131   bool registeredClaimFile = false;
132   bool registeredAllSymbolsRead = false;
133   bool registeredCleanup = false;
134
135   for (; tv->tv_tag != LDPT_NULL; ++tv) {
136     switch (tv->tv_tag) {
137       case LDPT_API_VERSION:
138         api_version = tv->tv_u.tv_val;
139         break;
140       case LDPT_GOLD_VERSION:  // major * 100 + minor
141         gold_version = tv->tv_u.tv_val;
142         break;
143       case LDPT_OUTPUT_NAME:
144         output_name = tv->tv_u.tv_string;
145         break;
146       case LDPT_LINKER_OUTPUT:
147         switch (tv->tv_u.tv_val) {
148           case LDPO_REL:  // .o
149           case LDPO_DYN:  // .so
150             output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
151             break;
152           case LDPO_EXEC:  // .exe
153             output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
154             break;
155           default:
156             (*message)(LDPL_ERROR, "Unknown output file type %d",
157                        tv->tv_u.tv_val);
158             return LDPS_ERR;
159         }
160         // TODO: add an option to disable PIC.
161         //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
162         break;
163       case LDPT_OPTION:
164         options::process_plugin_option(tv->tv_u.tv_string);
165         break;
166       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
167         ld_plugin_register_claim_file callback;
168         callback = tv->tv_u.tv_register_claim_file;
169
170         if ((*callback)(claim_file_hook) != LDPS_OK)
171           return LDPS_ERR;
172
173         registeredClaimFile = true;
174       } break;
175       case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
176         ld_plugin_register_all_symbols_read callback;
177         callback = tv->tv_u.tv_register_all_symbols_read;
178
179         if ((*callback)(all_symbols_read_hook) != LDPS_OK)
180           return LDPS_ERR;
181
182         registeredAllSymbolsRead = true;
183       } break;
184       case LDPT_REGISTER_CLEANUP_HOOK: {
185         ld_plugin_register_cleanup callback;
186         callback = tv->tv_u.tv_register_cleanup;
187
188         if ((*callback)(cleanup_hook) != LDPS_OK)
189           return LDPS_ERR;
190
191         registeredCleanup = true;
192       } break;
193       case LDPT_ADD_SYMBOLS:
194         add_symbols = tv->tv_u.tv_add_symbols;
195         break;
196       case LDPT_GET_SYMBOLS:
197         get_symbols = tv->tv_u.tv_get_symbols;
198         break;
199       case LDPT_ADD_INPUT_FILE:
200         add_input_file = tv->tv_u.tv_add_input_file;
201         break;
202       case LDPT_ADD_INPUT_LIBRARY:
203         add_input_library = tv->tv_u.tv_add_input_file;
204         break;
205       case LDPT_SET_EXTRA_LIBRARY_PATH:
206         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
207         break;
208       case LDPT_MESSAGE:
209         message = tv->tv_u.tv_message;
210         break;
211       default:
212         break;
213     }
214   }
215
216   if (!registeredClaimFile) {
217     (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
218     return LDPS_ERR;
219   }
220   if (!add_symbols) {
221     (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
222     return LDPS_ERR;
223   }
224
225   return LDPS_OK;
226 }
227
228 /// claim_file_hook - called by gold to see whether this file is one that
229 /// our plugin can handle. We'll try to open it and register all the symbols
230 /// with add_symbol if possible.
231 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
232                                         int *claimed) {
233   void *buf = NULL;
234   if (file->offset) {
235     // Gold has found what might be IR part-way inside of a file, such as
236     // an .a archive.
237     if (lseek(file->fd, file->offset, SEEK_SET) == -1) {
238       (*message)(LDPL_ERROR,
239                  "Failed to seek to archive member of %s at offset %d: %s\n",
240                  file->name,
241                  file->offset, sys::StrError(errno).c_str());
242       return LDPS_ERR;
243     }
244     buf = malloc(file->filesize);
245     if (!buf) {
246       (*message)(LDPL_ERROR,
247                  "Failed to allocate buffer for archive member of size: %d\n",
248                  file->filesize);
249       return LDPS_ERR;
250     }
251     if (read(file->fd, buf, file->filesize) != file->filesize) {
252       (*message)(LDPL_ERROR,
253                  "Failed to read archive member of %s at offset %d: %s\n",
254                  file->name,
255                  file->offset,
256                  sys::StrError(errno).c_str());
257       free(buf);
258       return LDPS_ERR;
259     }
260     if (!lto_module_is_object_file_in_memory(buf, file->filesize)) {
261       free(buf);
262       return LDPS_OK;
263     }
264   } else if (!lto_module_is_object_file(file->name))
265     return LDPS_OK;
266
267   *claimed = 1;
268   Modules.resize(Modules.size() + 1);
269   claimed_file &cf = Modules.back();
270
271   cf.M = buf ? lto_module_create_from_memory(buf, file->filesize) :
272                lto_module_create(file->name);
273   free(buf);
274   if (!cf.M) {
275     (*message)(LDPL_ERROR, "Failed to create LLVM module: %s",
276                lto_get_error_message());
277     return LDPS_ERR;
278   }
279   cf.handle = file->handle;
280   unsigned sym_count = lto_module_get_num_symbols(cf.M);
281   cf.syms.reserve(sym_count);
282
283   for (unsigned i = 0; i != sym_count; ++i) {
284     lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i);
285     if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
286       continue;
287
288     cf.syms.push_back(ld_plugin_symbol());
289     ld_plugin_symbol &sym = cf.syms.back();
290     sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i));
291     sym.version = NULL;
292
293     int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
294     switch (scope) {
295       case LTO_SYMBOL_SCOPE_HIDDEN:
296         sym.visibility = LDPV_HIDDEN;
297         break;
298       case LTO_SYMBOL_SCOPE_PROTECTED:
299         sym.visibility = LDPV_PROTECTED;
300         break;
301       case 0: // extern
302       case LTO_SYMBOL_SCOPE_DEFAULT:
303         sym.visibility = LDPV_DEFAULT;
304         break;
305       default:
306         (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
307         return LDPS_ERR;
308     }
309
310     int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
311     switch (definition) {
312       case LTO_SYMBOL_DEFINITION_REGULAR:
313         sym.def = LDPK_DEF;
314         break;
315       case LTO_SYMBOL_DEFINITION_UNDEFINED:
316         sym.def = LDPK_UNDEF;
317         break;
318       case LTO_SYMBOL_DEFINITION_TENTATIVE:
319         sym.def = LDPK_COMMON;
320         break;
321       case LTO_SYMBOL_DEFINITION_WEAK:
322         sym.def = LDPK_WEAKDEF;
323         break;
324       case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
325         sym.def = LDPK_WEAKUNDEF;
326         break;
327       default:
328         (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
329         return LDPS_ERR;
330     }
331
332     // LLVM never emits COMDAT.
333     sym.size = 0;
334     sym.comdat_key = NULL;
335
336     sym.resolution = LDPR_UNKNOWN;
337   }
338
339   cf.syms.reserve(cf.syms.size());
340
341   if (!cf.syms.empty()) {
342     if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
343       (*message)(LDPL_ERROR, "Unable to add symbols!");
344       return LDPS_ERR;
345     }
346   }
347
348   return LDPS_OK;
349 }
350
351 /// all_symbols_read_hook - gold informs us that all symbols have been read.
352 /// At this point, we use get_symbols to see if any of our definitions have
353 /// been overridden by a native object file. Then, perform optimization and
354 /// codegen.
355 static ld_plugin_status all_symbols_read_hook(void) {
356   lto_code_gen_t cg = lto_codegen_create();
357
358   for (std::list<claimed_file>::iterator I = Modules.begin(),
359        E = Modules.end(); I != E; ++I)
360     lto_codegen_add_module(cg, I->M);
361
362   std::ofstream api_file;
363   if (options::generate_api_file) {
364     api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc);
365     if (!api_file.is_open()) {
366       (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing.");
367       abort();
368     }
369   }
370
371   // If we don't preserve any symbols, libLTO will assume that all symbols are
372   // needed. Keep all symbols unless we're producing a final executable.
373   bool anySymbolsPreserved = false;
374   for (std::list<claimed_file>::iterator I = Modules.begin(),
375          E = Modules.end(); I != E; ++I) {
376     (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
377     for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
378       if (I->syms[i].resolution == LDPR_PREVAILING_DEF) {
379         lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name);
380         anySymbolsPreserved = true;
381
382         if (options::generate_api_file)
383           api_file << I->syms[i].name << "\n";
384       }
385     }
386   }
387
388   if (options::generate_api_file)
389     api_file.close();
390
391   if (!anySymbolsPreserved) {
392     // All of the IL is unnecessary!
393     lto_codegen_dispose(cg);
394     return LDPS_OK;
395   }
396
397   lto_codegen_set_pic_model(cg, output_type);
398   lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF);
399   if (!options::as_path.empty()) {
400     sys::Path p = sys::Program::FindProgramByName(options::as_path);
401     lto_codegen_set_assembler_path(cg, p.c_str());
402   }
403   // Pass through extra options to the code generator.
404   if (!options::extra.empty()) {
405     for (std::vector<std::string>::iterator it = options::extra.begin();
406          it != options::extra.end(); ++it) {
407       lto_codegen_debug_options(cg, (*it).c_str());
408     }
409   }
410
411
412   if (options::generate_bc_file != options::BC_NO) {
413     std::string path;
414     if (options::generate_bc_file == options::BC_ONLY)
415       path = output_name;
416     else if (!options::bc_path.empty())
417       path = options::bc_path;
418     else
419       path = output_name + ".bc";
420     bool err = lto_codegen_write_merged_modules(cg, path.c_str());
421     if (err)
422       (*message)(LDPL_FATAL, "Failed to write the output file.");
423     if (options::generate_bc_file == options::BC_ONLY)
424       exit(0);
425   }
426   size_t bufsize = 0;
427   const char *buffer = static_cast<const char *>(lto_codegen_compile(cg,
428                                                                      &bufsize));
429
430   std::string ErrMsg;
431
432   sys::Path uniqueObjPath("/tmp/llvmgold.o");
433   if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) {
434     (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
435     return LDPS_ERR;
436   }
437   raw_fd_ostream objFile(uniqueObjPath.c_str(), ErrMsg,
438                          raw_fd_ostream::F_Binary);
439   if (!ErrMsg.empty()) {
440     (*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
441     return LDPS_ERR;
442   }
443
444   objFile.write(buffer, bufsize);
445   objFile.close();
446
447   lto_codegen_dispose(cg);
448
449   if ((*add_input_file)(uniqueObjPath.c_str()) != LDPS_OK) {
450     (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
451     (*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str());
452     return LDPS_ERR;
453   }
454
455   if (!options::extra_library_path.empty() &&
456       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
457     (*message)(LDPL_ERROR, "Unable to set the extra library path.");
458     return LDPS_ERR;
459   }
460
461   for (std::vector<std::string>::iterator i = options::pass_through.begin(),
462                                           e = options::pass_through.end();
463        i != e; ++i) {
464     std::string &item = *i;
465     const char *item_p = item.c_str();
466     if (llvm::StringRef(item).startswith("-l")) {
467       if (add_input_library(item_p + 2) != LDPS_OK) {
468         (*message)(LDPL_ERROR, "Unable to add library to the link.");
469         return LDPS_ERR;
470       }
471     } else {
472       if (add_input_file(item_p) != LDPS_OK) {
473         (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
474         return LDPS_ERR;
475       }
476     }
477   }
478
479   Cleanup.push_back(uniqueObjPath);
480
481   return LDPS_OK;
482 }
483
484 static ld_plugin_status cleanup_hook(void) {
485   std::string ErrMsg;
486
487   for (int i = 0, e = Cleanup.size(); i != e; ++i)
488     if (Cleanup[i].eraseFromDisk(false, &ErrMsg))
489       (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
490                  ErrMsg.c_str());
491
492   return LDPS_OK;
493 }