d428c6910a815e573af8b5117fe1aaf0890aae51
[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 "llvm-c/lto.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/LTO/LTOCodeGenerator.h"
20 #include "llvm/LTO/LTOModule.h"
21 #include "llvm/Support/Errno.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/Program.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/ToolOutputFile.h"
28 #include <cerrno>
29 #include <cstdlib>
30 #include <cstring>
31 #include <list>
32 #include <plugin-api.h>
33 #include <system_error>
34 #include <vector>
35
36 // Support Windows/MinGW crazyness.
37 #ifdef _WIN32
38 # include <io.h>
39 # define lseek _lseek
40 # define read _read
41 #endif
42
43 #ifndef LDPO_PIE
44 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
45 // Precise and Debian Wheezy (binutils 2.23 is required)
46 # define LDPO_PIE 3
47 #endif
48
49 using namespace llvm;
50
51 namespace {
52 struct claimed_file {
53   void *handle;
54   std::vector<ld_plugin_symbol> syms;
55 };
56 }
57
58 static ld_plugin_status discard_message(int level, const char *format, ...) {
59   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
60   // callback in the transfer vector. This should never be called.
61   abort();
62 }
63
64 static ld_plugin_add_symbols add_symbols = NULL;
65 static ld_plugin_get_symbols get_symbols = NULL;
66 static ld_plugin_add_input_file add_input_file = NULL;
67 static ld_plugin_set_extra_library_path set_extra_library_path = NULL;
68 static ld_plugin_get_view get_view = NULL;
69 static ld_plugin_message message = discard_message;
70 static lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
71 static std::string output_name = "";
72 static std::list<claimed_file> Modules;
73 static std::vector<std::string> Cleanup;
74 static LTOCodeGenerator *CodeGen = nullptr;
75 static StringSet<> CannotBeHidden;
76 static llvm::TargetOptions TargetOpts;
77
78 namespace options {
79   enum generate_bc { BC_NO, BC_ALSO, BC_ONLY };
80   static bool generate_api_file = false;
81   static generate_bc generate_bc_file = BC_NO;
82   static std::string bc_path;
83   static std::string obj_path;
84   static std::string extra_library_path;
85   static std::string triple;
86   static std::string mcpu;
87   // Additional options to pass into the code generator.
88   // Note: This array will contain all plugin options which are not claimed
89   // as plugin exclusive to pass to the code generator.
90   // For example, "generate-api-file" and "as"options are for the plugin
91   // use only and will not be passed.
92   static std::vector<const char *> extra;
93
94   static void process_plugin_option(const char* opt_)
95   {
96     if (opt_ == NULL)
97       return;
98     llvm::StringRef opt = opt_;
99
100     if (opt == "generate-api-file") {
101       generate_api_file = true;
102     } else if (opt.startswith("mcpu=")) {
103       mcpu = opt.substr(strlen("mcpu="));
104     } else if (opt.startswith("extra-library-path=")) {
105       extra_library_path = opt.substr(strlen("extra_library_path="));
106     } else if (opt.startswith("mtriple=")) {
107       triple = opt.substr(strlen("mtriple="));
108     } else if (opt.startswith("obj-path=")) {
109       obj_path = opt.substr(strlen("obj-path="));
110     } else if (opt == "emit-llvm") {
111       generate_bc_file = BC_ONLY;
112     } else if (opt == "also-emit-llvm") {
113       generate_bc_file = BC_ALSO;
114     } else if (opt.startswith("also-emit-llvm=")) {
115       llvm::StringRef path = opt.substr(strlen("also-emit-llvm="));
116       generate_bc_file = BC_ALSO;
117       if (!bc_path.empty()) {
118         (*message)(LDPL_WARNING, "Path to the output IL file specified twice. "
119                    "Discarding %s", opt_);
120       } else {
121         bc_path = path;
122       }
123     } else {
124       // Save this option to pass to the code generator.
125       extra.push_back(opt_);
126     }
127   }
128 }
129
130 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
131                                         int *claimed);
132 static ld_plugin_status all_symbols_read_hook(void);
133 static ld_plugin_status cleanup_hook(void);
134
135 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
136 ld_plugin_status onload(ld_plugin_tv *tv) {
137   InitializeAllTargetInfos();
138   InitializeAllTargets();
139   InitializeAllTargetMCs();
140   InitializeAllAsmParsers();
141   InitializeAllAsmPrinters();
142
143   // We're given a pointer to the first transfer vector. We read through them
144   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
145   // contain pointers to functions that we need to call to register our own
146   // hooks. The others are addresses of functions we can use to call into gold
147   // for services.
148
149   bool registeredClaimFile = false;
150   bool RegisteredAllSymbolsRead = false;
151
152   for (; tv->tv_tag != LDPT_NULL; ++tv) {
153     switch (tv->tv_tag) {
154       case LDPT_OUTPUT_NAME:
155         output_name = tv->tv_u.tv_string;
156         break;
157       case LDPT_LINKER_OUTPUT:
158         switch (tv->tv_u.tv_val) {
159           case LDPO_REL:  // .o
160           case LDPO_DYN:  // .so
161           case LDPO_PIE:  // position independent executable
162             output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
163             break;
164           case LDPO_EXEC:  // .exe
165             output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
166             break;
167           default:
168             (*message)(LDPL_ERROR, "Unknown output file type %d",
169                        tv->tv_u.tv_val);
170             return LDPS_ERR;
171         }
172         break;
173       case LDPT_OPTION:
174         options::process_plugin_option(tv->tv_u.tv_string);
175         break;
176       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
177         ld_plugin_register_claim_file callback;
178         callback = tv->tv_u.tv_register_claim_file;
179
180         if ((*callback)(claim_file_hook) != LDPS_OK)
181           return LDPS_ERR;
182
183         registeredClaimFile = true;
184       } break;
185       case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
186         ld_plugin_register_all_symbols_read callback;
187         callback = tv->tv_u.tv_register_all_symbols_read;
188
189         if ((*callback)(all_symbols_read_hook) != LDPS_OK)
190           return LDPS_ERR;
191
192         RegisteredAllSymbolsRead = true;
193       } break;
194       case LDPT_REGISTER_CLEANUP_HOOK: {
195         ld_plugin_register_cleanup callback;
196         callback = tv->tv_u.tv_register_cleanup;
197
198         if ((*callback)(cleanup_hook) != LDPS_OK)
199           return LDPS_ERR;
200       } break;
201       case LDPT_ADD_SYMBOLS:
202         add_symbols = tv->tv_u.tv_add_symbols;
203         break;
204       case LDPT_GET_SYMBOLS_V2:
205         get_symbols = tv->tv_u.tv_get_symbols;
206         break;
207       case LDPT_ADD_INPUT_FILE:
208         add_input_file = tv->tv_u.tv_add_input_file;
209         break;
210       case LDPT_SET_EXTRA_LIBRARY_PATH:
211         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
212         break;
213       case LDPT_GET_VIEW:
214         get_view = tv->tv_u.tv_get_view;
215         break;
216       case LDPT_MESSAGE:
217         message = tv->tv_u.tv_message;
218         break;
219       default:
220         break;
221     }
222   }
223
224   if (!registeredClaimFile) {
225     (*message)(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
226     return LDPS_ERR;
227   }
228   if (!add_symbols) {
229     (*message)(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
230     return LDPS_ERR;
231   }
232
233   if (!RegisteredAllSymbolsRead)
234     return LDPS_OK;
235
236   CodeGen = new LTOCodeGenerator();
237
238   // Pass through extra options to the code generator.
239   if (!options::extra.empty()) {
240     for (const char *Opt : options::extra)
241       CodeGen->setCodeGenDebugOptions(Opt);
242   }
243
244   CodeGen->parseCodeGenDebugOptions();
245   if (MAttrs.size()) {
246     std::string Attrs;
247     for (unsigned I = 0; I < MAttrs.size(); ++I) {
248       if (I > 0)
249         Attrs.append(",");
250       Attrs.append(MAttrs[I]);
251     }
252     CodeGen->setAttr(Attrs.c_str());
253   }
254
255   TargetOpts = InitTargetOptionsFromCodeGenFlags();
256   CodeGen->setTargetOptions(TargetOpts);
257
258   return LDPS_OK;
259 }
260
261 /// Called by gold to see whether this file is one that our plugin can handle.
262 /// We'll try to open it and register all the symbols with add_symbol if
263 /// possible.
264 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
265                                         int *claimed) {
266   const void *view;
267   std::unique_ptr<MemoryBuffer> buffer;
268   if (get_view) {
269     if (get_view(file->handle, &view) != LDPS_OK) {
270       (*message)(LDPL_ERROR, "Failed to get a view of %s", file->name);
271       return LDPS_ERR;
272     }
273   } else {
274     int64_t offset = 0;
275     // Gold has found what might be IR part-way inside of a file, such as
276     // an .a archive.
277     if (file->offset) {
278       offset = file->offset;
279     }
280     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
281         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
282                                        offset);
283     if (std::error_code EC = BufferOrErr.getError()) {
284       (*message)(LDPL_ERROR, EC.message().c_str());
285       return LDPS_ERR;
286     }
287     buffer = std::move(BufferOrErr.get());
288     view = buffer->getBufferStart();
289   }
290
291   if (!LTOModule::isBitcodeFile(view, file->filesize))
292     return LDPS_OK;
293
294   *claimed = 1;
295
296   std::string Error;
297   LTOModule *M =
298       LTOModule::createFromBuffer(view, file->filesize, TargetOpts, Error);
299   if (!M) {
300     (*message)(LDPL_ERROR,
301                "LLVM gold plugin has failed to create LTO module: %s",
302                Error.c_str());
303     return LDPS_ERR;
304   }
305
306   Modules.resize(Modules.size() + 1);
307   claimed_file &cf = Modules.back();
308
309   if (!options::triple.empty())
310     M->setTargetTriple(options::triple.c_str());
311
312   cf.handle = file->handle;
313   unsigned sym_count = M->getSymbolCount();
314   cf.syms.reserve(sym_count);
315
316   for (unsigned i = 0; i != sym_count; ++i) {
317     lto_symbol_attributes attrs = M->getSymbolAttributes(i);
318     if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
319       continue;
320
321     cf.syms.push_back(ld_plugin_symbol());
322     ld_plugin_symbol &sym = cf.syms.back();
323     sym.name = strdup(M->getSymbolName(i));
324     sym.version = NULL;
325
326     int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
327     bool CanBeHidden = scope == LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
328     if (!CanBeHidden)
329       CannotBeHidden.insert(sym.name);
330     switch (scope) {
331       case LTO_SYMBOL_SCOPE_HIDDEN:
332         sym.visibility = LDPV_HIDDEN;
333         break;
334       case LTO_SYMBOL_SCOPE_PROTECTED:
335         sym.visibility = LDPV_PROTECTED;
336         break;
337       case 0: // extern
338       case LTO_SYMBOL_SCOPE_DEFAULT:
339       case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN:
340         sym.visibility = LDPV_DEFAULT;
341         break;
342       default:
343         (*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
344         return LDPS_ERR;
345     }
346
347     int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
348     sym.comdat_key = NULL;
349     switch (definition) {
350       case LTO_SYMBOL_DEFINITION_REGULAR:
351         sym.def = LDPK_DEF;
352         break;
353       case LTO_SYMBOL_DEFINITION_UNDEFINED:
354         sym.def = LDPK_UNDEF;
355         break;
356       case LTO_SYMBOL_DEFINITION_TENTATIVE:
357         sym.def = LDPK_COMMON;
358         break;
359       case LTO_SYMBOL_DEFINITION_WEAK:
360         sym.comdat_key = sym.name;
361         sym.def = LDPK_WEAKDEF;
362         break;
363       case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
364         sym.def = LDPK_WEAKUNDEF;
365         break;
366       default:
367         (*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
368         return LDPS_ERR;
369     }
370
371     sym.size = 0;
372
373     sym.resolution = LDPR_UNKNOWN;
374   }
375
376   cf.syms.reserve(cf.syms.size());
377
378   if (!cf.syms.empty()) {
379     if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
380       (*message)(LDPL_ERROR, "Unable to add symbols!");
381       return LDPS_ERR;
382     }
383   }
384
385   if (CodeGen) {
386     std::string Error;
387     if (!CodeGen->addModule(M, Error)) {
388       (*message)(LDPL_ERROR, "Error linking module: %s", Error.c_str());
389       return LDPS_ERR;
390     }
391   }
392
393   delete M;
394
395   return LDPS_OK;
396 }
397
398 static bool mustPreserve(const claimed_file &F, int i) {
399   if (F.syms[i].resolution == LDPR_PREVAILING_DEF)
400     return true;
401   if (F.syms[i].resolution == LDPR_PREVAILING_DEF_IRONLY_EXP)
402     return CannotBeHidden.count(F.syms[i].name);
403   return false;
404 }
405
406 /// all_symbols_read_hook - gold informs us that all symbols have been read.
407 /// At this point, we use get_symbols to see if any of our definitions have
408 /// been overridden by a native object file. Then, perform optimization and
409 /// codegen.
410 static ld_plugin_status all_symbols_read_hook(void) {
411   // FIXME: raw_fd_ostream should be able to represent an unopened file.
412   std::unique_ptr<raw_fd_ostream> api_file;
413
414   assert(CodeGen);
415
416   if (options::generate_api_file) {
417     std::string Error;
418     api_file.reset(new raw_fd_ostream("apifile.txt", Error, sys::fs::F_None));
419     if (!Error.empty())
420       (*message)(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
421                  Error.c_str());
422   }
423
424   for (std::list<claimed_file>::iterator I = Modules.begin(),
425          E = Modules.end(); I != E; ++I) {
426     if (I->syms.empty())
427       continue;
428     (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
429     for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
430       if (mustPreserve(*I, i)) {
431         CodeGen->addMustPreserveSymbol(I->syms[i].name);
432
433         if (options::generate_api_file)
434           (*api_file) << I->syms[i].name << "\n";
435       }
436     }
437   }
438
439   CodeGen->setCodePICModel(output_type);
440   CodeGen->setDebugInfo(LTO_DEBUG_MODEL_DWARF);
441   if (!options::mcpu.empty())
442     CodeGen->setCpu(options::mcpu.c_str());
443
444   if (options::generate_bc_file != options::BC_NO) {
445     std::string path;
446     if (options::generate_bc_file == options::BC_ONLY)
447       path = output_name;
448     else if (!options::bc_path.empty())
449       path = options::bc_path;
450     else
451       path = output_name + ".bc";
452     std::string Error;
453     if (!CodeGen->writeMergedModules(path.c_str(), Error))
454       (*message)(LDPL_FATAL, "Failed to write the output file.");
455     if (options::generate_bc_file == options::BC_ONLY) {
456       delete CodeGen;
457       exit(0);
458     }
459   }
460
461   std::string ObjPath;
462   {
463     const char *Temp;
464     std::string Error;
465     if (!CodeGen->compile_to_file(&Temp, /*DisableOpt*/ false, /*DisableInline*/
466                                   false, /*DisableGVNLoadPRE*/ false, Error))
467       (*message)(LDPL_ERROR, "Could not produce a combined object file\n");
468     ObjPath = Temp;
469   }
470
471   delete CodeGen;
472   for (std::list<claimed_file>::iterator I = Modules.begin(),
473          E = Modules.end(); I != E; ++I) {
474     for (unsigned i = 0; i != I->syms.size(); ++i) {
475       ld_plugin_symbol &sym = I->syms[i];
476       free(sym.name);
477     }
478   }
479
480   if ((*add_input_file)(ObjPath.c_str()) != LDPS_OK) {
481     (*message)(LDPL_ERROR, "Unable to add .o file to the link.");
482     (*message)(LDPL_ERROR, "File left behind in: %s", ObjPath.c_str());
483     return LDPS_ERR;
484   }
485
486   if (!options::extra_library_path.empty() &&
487       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK) {
488     (*message)(LDPL_ERROR, "Unable to set the extra library path.");
489     return LDPS_ERR;
490   }
491
492   if (options::obj_path.empty())
493     Cleanup.push_back(ObjPath);
494
495   return LDPS_OK;
496 }
497
498 static ld_plugin_status cleanup_hook(void) {
499   for (int i = 0, e = Cleanup.size(); i != e; ++i) {
500     std::error_code EC = sys::fs::remove(Cleanup[i]);
501     if (EC)
502       (*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
503                  EC.message().c_str());
504   }
505
506   return LDPS_OK;
507 }