Misc enhancements to LTO:
[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" // plugin-api.h requires HAVE_STDINT_H
16 #include "plugin-api.h"
17 #include "llvm-c/lto.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/Support/Errno.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/Program.h"
24 #include "llvm/Support/ToolOutputFile.h"
25 #include "llvm/Support/system_error.h"
26 #include <cerrno>
27 #include <cstdlib>
28 #include <cstring>
29 #include <fstream>
30 #include <list>
31 #include <vector>
32
33 // Support Windows/MinGW crazyness.
34 #ifdef _WIN32
35 # include <io.h>
36 # define lseek _lseek
37 # define read _read
38 #endif
39
40 using namespace llvm;
41
42 namespace {
43   ld_plugin_status discard_message(int level, const char *format, ...) {
44     // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
45     // callback in the transfer vector. This should never be called.
46     abort();
47   }
48
49   ld_plugin_add_symbols add_symbols = NULL;
50   ld_plugin_get_symbols get_symbols = NULL;
51   ld_plugin_add_input_file add_input_file = NULL;
52   ld_plugin_add_input_library add_input_library = NULL;
53   ld_plugin_set_extra_library_path set_extra_library_path = NULL;
54   ld_plugin_get_view get_view = NULL;
55   ld_plugin_message message = discard_message;
56
57   int api_version = 0;
58   int gold_version = 0;
59
60   struct claimed_file {
61     void *handle;
62     std::vector<ld_plugin_symbol> syms;
63   };
64
65   lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
66   std::string output_name = "";
67   std::list<claimed_file> Modules;
68   std::vector<std::string> Cleanup;
69   lto_code_gen_t code_gen = NULL;
70 }
71
72 namespace options {
73   enum generate_bc { BC_NO, BC_ALSO, BC_ONLY };
74   static bool generate_api_file = false;
75   static generate_bc generate_bc_file = BC_NO;
76   static std::string bc_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<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("mtriple=")) {
100       triple = opt.substr(strlen("mtriple="));
101     } else if (opt == "emit-llvm") {
102       generate_bc_file = BC_ONLY;
103     } else if (opt == "also-emit-llvm") {
104       generate_bc_file = BC_ALSO;
105     } else if (opt.startswith("also-emit-llvm=")) {
106       llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
107       generate_bc_file = BC_ALSO;
108       if (!bc_path.empty()) {
109         (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
110                    "Discarding %s", opt_);
111       } else {
112         bc_path = path;
113       }
114     } else {
115       // Save this option to pass to the code generator.
116       extra.push_back(opt);
117     }
118   }
119 }
120
121 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
122                                         int *claimed);
123 static ld_plugin_status all_symbols_read_hook(void);
124 static ld_plugin_status cleanup_hook(void);
125
126 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
127 ld_plugin_status onload(ld_plugin_tv *tv) {
128   // We're given a pointer to the first transfer vector. We read through them
129   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
130   // contain pointers to functions that we need to call to register our own
131   // hooks. The others are addresses of functions we can use to call into gold
132   // for services.
133
134   bool registeredClaimFile = false;
135
136   for (; tv->tv_tag != LDPT_NULL; ++tv) {
137     switch (tv->tv_tag) {
138       case LDPT_API_VERSION:
139         api_version = tv->tv_u.tv_val;
140         break;
141       case LDPT_GOLD_VERSION:  // major * 100 + minor
142         gold_version = tv->tv_u.tv_val;
143         break;
144       case LDPT_OUTPUT_NAME:
145         output_name = tv->tv_u.tv_string;
146         break;
147       case LDPT_LINKER_OUTPUT:
148         switch (tv->tv_u.tv_val) {
149           case LDPO_REL:  // .o
150           case LDPO_DYN:  // .so
151           // FIXME: Replace 3 with LDPO_PIE once that is in a released binutils.
152           case 3: // position independent executable
153             output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
154             break;
155           case LDPO_EXEC:  // .exe
156             output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
157             break;
158           default:
159             (*message)(LDPL_ERROR, "Unknown output file type %d",
160                        tv->tv_u.tv_val);
161             return LDPS_ERR;
162         }
163         // TODO: add an option to disable PIC.
164         //output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
165         break;
166       case LDPT_OPTION:
167         options::process_plugin_option(tv->tv_u.tv_string);
168         break;
169       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
170         ld_plugin_register_claim_file callback;
171         callback = tv->tv_u.tv_register_claim_file;
172
173         if ((*callback)(claim_file_hook) != LDPS_OK)
174           return LDPS_ERR;
175
176         registeredClaimFile = true;
177       } break;
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;
181
182         if ((*callback)(all_symbols_read_hook) != LDPS_OK)
183           return LDPS_ERR;
184
185         code_gen = lto_codegen_create();
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_GET_VIEW:
210         get_view = tv->tv_u.tv_get_view;
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   const void *view;
239   OwningPtr<MemoryBuffer> buffer;
240   if (get_view) {
241     if (get_view(file->handle, &view) != LDPS_OK) {
242       (*message)(LDPL_ERROR, "Failed to get a view of %s", file->name);
243       return LDPS_ERR;
244     }
245   } else {
246     int64_t offset = 0;
247     // Gold has found what might be IR part-way inside of a file, such as
248     // an .a archive.
249     if (file->offset) {
250       offset = file->offset;
251     }
252     if (error_code ec = MemoryBuffer::getOpenFileSlice(
253             file->fd, file->name, buffer, file->filesize, offset)) {
254       (*message)(LDPL_ERROR, ec.message().c_str());
255       return LDPS_ERR;
256     }
257     view = buffer->getBufferStart();
258   }
259
260   if (!lto_module_is_object_file_in_memory(view, file->filesize))
261     return LDPS_OK;
262
263   M = lto_module_create_from_memory(view, file->filesize);
264   if (!M) {
265     if (const char* msg = lto_get_error_message()) {
266       (*message)(LDPL_ERROR,
267                  "LLVM gold plugin has failed to create LTO module: %s",
268                  msg);
269       return LDPS_ERR;
270     }
271     return LDPS_OK;
272   }
273
274   *claimed = 1;
275   Modules.resize(Modules.size() + 1);
276   claimed_file &cf = Modules.back();
277
278   if (!options::triple.empty())
279     lto_module_set_target_triple(M, options::triple.c_str());
280
281   cf.handle = file->handle;
282   unsigned sym_count = lto_module_get_num_symbols(M);
283   cf.syms.reserve(sym_count);
284
285   for (unsigned i = 0; i != sym_count; ++i) {
286     lto_symbol_attributes attrs = lto_module_get_symbol_attribute(M, i);
287     if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
288       continue;
289
290     cf.syms.push_back(ld_plugin_symbol());
291     ld_plugin_symbol &sym = cf.syms.back();
292     sym.name = const_cast<char *>(lto_module_get_symbol_name(M, i));
293     sym.name = strdup(sym.name);
294     sym.version = NULL;
295
296     int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
297     switch (scope) {
298       case LTO_SYMBOL_SCOPE_HIDDEN:
299         sym.visibility = LDPV_HIDDEN;
300         break;
301       case LTO_SYMBOL_SCOPE_PROTECTED:
302         sym.visibility = LDPV_PROTECTED;
303         break;
304       case 0: // extern
305       case LTO_SYMBOL_SCOPE_DEFAULT:
306         sym.visibility = LDPV_DEFAULT;
307         break;
308       default:
309         (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
310         return LDPS_ERR;
311     }
312
313     int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
314     sym.comdat_key = NULL;
315     switch (definition) {
316       case LTO_SYMBOL_DEFINITION_REGULAR:
317         sym.def = LDPK_DEF;
318         break;
319       case LTO_SYMBOL_DEFINITION_UNDEFINED:
320         sym.def = LDPK_UNDEF;
321         break;
322       case LTO_SYMBOL_DEFINITION_TENTATIVE:
323         sym.def = LDPK_COMMON;
324         break;
325       case LTO_SYMBOL_DEFINITION_WEAK:
326         sym.comdat_key = sym.name;
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     sym.size = 0;
338
339     sym.resolution = LDPR_UNKNOWN;
340   }
341
342   cf.syms.reserve(cf.syms.size());
343
344   if (!cf.syms.empty()) {
345     if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
346       (*message)(LDPL_ERROR, "Unable to add symbols!");
347       return LDPS_ERR;
348     }
349   }
350
351   if (code_gen)
352     lto_codegen_add_module(code_gen, M);
353
354   lto_module_dispose(M);
355
356   return LDPS_OK;
357 }
358
359 /// all_symbols_read_hook - gold informs us that all symbols have been read.
360 /// At this point, we use get_symbols to see if any of our definitions have
361 /// been overridden by a native object file. Then, perform optimization and
362 /// codegen.
363 static ld_plugin_status all_symbols_read_hook(void) {
364   std::ofstream api_file;
365   assert(code_gen);
366
367   if (options::generate_api_file) {
368     api_file.open("apifile.txt", std::ofstream::out | std::ofstream::trunc);
369     if (!api_file.is_open()) {
370       (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing.");
371       abort();
372     }
373   }
374
375   for (std::list<claimed_file>::iterator I = Modules.begin(),
376          E = Modules.end(); I != E; ++I) {
377     if (I->syms.empty())
378       continue;
379     (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
380     for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
381       if (I->syms[i].resolution == LDPR_PREVAILING_DEF) {
382         lto_codegen_add_must_preserve_symbol(code_gen, I->syms[i].name);
383
384         if (options::generate_api_file)
385           api_file << I->syms[i].name << "\n";
386       }
387     }
388   }
389
390   if (options::generate_api_file)
391     api_file.close();
392
393   lto_codegen_set_pic_model(code_gen, output_type);
394   lto_codegen_set_debug_model(code_gen, LTO_DEBUG_MODEL_DWARF);
395   if (!options::mcpu.empty())
396     lto_codegen_set_cpu(code_gen, options::mcpu.c_str());
397
398   // Pass through extra options to the code generator.
399   if (!options::extra.empty()) {
400     for (std::vector<std::string>::iterator it = options::extra.begin();
401          it != options::extra.end(); ++it) {
402       lto_codegen_debug_options(code_gen, (*it).c_str());
403     }
404   }
405
406   if (options::generate_bc_file != options::BC_NO) {
407     std::string path;
408     if (options::generate_bc_file == options::BC_ONLY)
409       path = output_name;
410     else if (!options::bc_path.empty())
411       path = options::bc_path;
412     else
413       path = output_name + ".bc";
414     bool err = lto_codegen_write_merged_modules(code_gen, path.c_str());
415     if (err)
416       (*message)(LDPL_FATAL, "Failed to write the output file.");
417     if (options::generate_bc_file == options::BC_ONLY)
418       exit(0);
419   }
420   const char *objPath;
421   if (lto_codegen_compile_to_file(code_gen, &objPath)) {
422     (*message)(LDPL_ERROR, "Could not produce a combined object file\n");
423   }
424
425   // Get files that need to be removed in cleanup_hook.
426   const char *ToRm;
427   lto_codegen_get_files_need_remove(code_gen, &ToRm);
428   while (*ToRm) {
429     Cleanup.push_back(std::string(ToRm));
430     ToRm += strlen(ToRm) + 1; 
431   }
432
433   lto_codegen_dispose(code_gen);
434   for (std::list<claimed_file>::iterator I = Modules.begin(),
435          E = Modules.end(); I != E; ++I) {
436     for (unsigned i = 0; i != I->syms.size(); ++i) {
437       ld_plugin_symbol &sym = I->syms[i];
438       free(sym.name);
439     }
440   }
441
442   if ((*add_input_file)(objPath) != LDPS_OK) {
443     (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
444     (*message)(LDPL_ERROR, "File left behind in: %s", objPath);
445     return LDPS_ERR;
446   }
447
448   if (!options::extra_library_path.empty() &&
449       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
450     (*message)(LDPL_ERROR, "Unable to set the extra library path.");
451     return LDPS_ERR;
452   }
453
454   return LDPS_OK;
455 }
456
457 static ld_plugin_status cleanup_hook(void) {
458   for (int i = 0, e = Cleanup.size(); i != e; ++i) {
459     const char *FN = Cleanup[i].c_str();
460     sys::fs::file_status Stat;
461     error_code EC = sys::fs::status(Twine(FN), Stat);
462     if (EC) {
463       (*message)(LDPL_ERROR, "Failed to stat '%s': %s", FN,
464                  EC.message().c_str());
465       continue;
466     }
467
468     uint32_t Dummy;
469     if (sys::fs::is_directory(FN))
470       EC = sys::fs::remove_all(Twine(FN), Dummy);
471     else
472       EC = sys::fs::remove(Twine(FN));
473
474     if (EC)
475       (*message)(LDPL_ERROR, "Failed to remove '%s': %s", FN,
476                  EC.message().c_str());
477   }
478
479   return LDPS_OK;
480 }