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