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