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