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