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/Bitcode/ReaderWriter.h"
16 #include "llvm/CodeGen/CommandFlags.h"
17 #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DiagnosticPrinter.h"
20 #include "llvm/LTO/Caching.h"
21 #include "llvm/LTO/LTO.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <list>
29 #include <map>
30 #include <plugin-api.h>
31 #include <string>
32 #include <system_error>
33 #include <utility>
34 #include <vector>
35 
36 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
37 // Precise and Debian Wheezy (binutils 2.23 is required)
38 #define LDPO_PIE 3
39 
40 #define LDPT_GET_SYMBOLS_V3 28
41 
42 using namespace llvm;
43 using namespace lto;
44 
45 static ld_plugin_status discard_message(int level, const char *format, ...) {
46   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
47   // callback in the transfer vector. This should never be called.
48   abort();
49 }
50 
51 static ld_plugin_release_input_file release_input_file = nullptr;
52 static ld_plugin_get_input_file get_input_file = nullptr;
53 static ld_plugin_message message = discard_message;
54 
55 namespace {
56 struct claimed_file {
57   void *handle;
58   void *leader_handle;
59   std::vector<ld_plugin_symbol> syms;
60   off_t filesize;
61   std::string name;
62 };
63 
64 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
65 struct PluginInputFile {
66   void *Handle;
67   std::unique_ptr<ld_plugin_input_file> File;
68 
69   PluginInputFile(void *Handle) : Handle(Handle) {
70     File = llvm::make_unique<ld_plugin_input_file>();
71     if (get_input_file(Handle, File.get()) != LDPS_OK)
72       message(LDPL_FATAL, "Failed to get file information");
73   }
74   ~PluginInputFile() {
75     // File would have been reset to nullptr if we moved this object
76     // to a new owner.
77     if (File)
78       if (release_input_file(Handle) != LDPS_OK)
79         message(LDPL_FATAL, "Failed to release file information");
80   }
81 
82   ld_plugin_input_file &file() { return *File; }
83 
84   PluginInputFile(PluginInputFile &&RHS) = default;
85   PluginInputFile &operator=(PluginInputFile &&RHS) = default;
86 };
87 
88 struct ResolutionInfo {
89   bool CanOmitFromDynSym = true;
90   bool DefaultVisibility = true;
91 };
92 
93 }
94 
95 static ld_plugin_add_symbols add_symbols = nullptr;
96 static ld_plugin_get_symbols get_symbols = nullptr;
97 static ld_plugin_add_input_file add_input_file = nullptr;
98 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
99 static ld_plugin_get_view get_view = nullptr;
100 static bool IsExecutable = false;
101 static Optional<Reloc::Model> RelocationModel;
102 static std::string output_name = "";
103 static std::list<claimed_file> Modules;
104 static DenseMap<int, void *> FDToLeaderHandle;
105 static StringMap<ResolutionInfo> ResInfo;
106 static std::vector<std::string> Cleanup;
107 static llvm::TargetOptions TargetOpts;
108 static size_t MaxTasks;
109 
110 namespace options {
111   enum OutputType {
112     OT_NORMAL,
113     OT_DISABLE,
114     OT_BC_ONLY,
115     OT_SAVE_TEMPS
116   };
117   static OutputType TheOutputType = OT_NORMAL;
118   static unsigned OptLevel = 2;
119   // Default parallelism of 0 used to indicate that user did not specify.
120   // Actual parallelism default value depends on implementation.
121   // Currently only affects ThinLTO, where the default is the
122   // hardware_concurrency.
123   static unsigned Parallelism = 0;
124   // Default regular LTO codegen parallelism (number of partitions).
125   static unsigned ParallelCodeGenParallelismLevel = 1;
126 #ifdef NDEBUG
127   static bool DisableVerify = true;
128 #else
129   static bool DisableVerify = false;
130 #endif
131   static std::string obj_path;
132   static std::string extra_library_path;
133   static std::string triple;
134   static std::string mcpu;
135   // When the thinlto plugin option is specified, only read the function
136   // the information from intermediate files and write a combined
137   // global index for the ThinLTO backends.
138   static bool thinlto = false;
139   // If false, all ThinLTO backend compilations through code gen are performed
140   // using multiple threads in the gold-plugin, before handing control back to
141   // gold. If true, write individual backend index files which reflect
142   // the import decisions, and exit afterwards. The assumption is
143   // that the build system will launch the backend processes.
144   static bool thinlto_index_only = false;
145   // If non-empty, holds the name of a file in which to write the list of
146   // oject files gold selected for inclusion in the link after symbol
147   // resolution (i.e. they had selected symbols). This will only be non-empty
148   // in the thinlto_index_only case. It is used to identify files, which may
149   // have originally been within archive libraries specified via
150   // --start-lib/--end-lib pairs, that should be included in the final
151   // native link process (since intervening function importing and inlining
152   // may change the symbol resolution detected in the final link and which
153   // files to include out of --start-lib/--end-lib libraries as a result).
154   static std::string thinlto_linked_objects_file;
155   // If true, when generating individual index files for distributed backends,
156   // also generate a "${bitcodefile}.imports" file at the same location for each
157   // bitcode file, listing the files it imports from in plain text. This is to
158   // support distributed build file staging.
159   static bool thinlto_emit_imports_files = false;
160   // Option to control where files for a distributed backend (the individual
161   // index files and optional imports files) are created.
162   // If specified, expects a string of the form "oldprefix:newprefix", and
163   // instead of generating these files in the same directory path as the
164   // corresponding bitcode file, will use a path formed by replacing the
165   // bitcode file's path prefix matching oldprefix with newprefix.
166   static std::string thinlto_prefix_replace;
167   // Optional path to a directory for caching ThinLTO objects.
168   static std::string cache_dir;
169   // Additional options to pass into the code generator.
170   // Note: This array will contain all plugin options which are not claimed
171   // as plugin exclusive to pass to the code generator.
172   static std::vector<const char *> extra;
173 
174   static void process_plugin_option(const char *opt_)
175   {
176     if (opt_ == nullptr)
177       return;
178     llvm::StringRef opt = opt_;
179 
180     if (opt.startswith("mcpu=")) {
181       mcpu = opt.substr(strlen("mcpu="));
182     } else if (opt.startswith("extra-library-path=")) {
183       extra_library_path = opt.substr(strlen("extra_library_path="));
184     } else if (opt.startswith("mtriple=")) {
185       triple = opt.substr(strlen("mtriple="));
186     } else if (opt.startswith("obj-path=")) {
187       obj_path = opt.substr(strlen("obj-path="));
188     } else if (opt == "emit-llvm") {
189       TheOutputType = OT_BC_ONLY;
190     } else if (opt == "save-temps") {
191       TheOutputType = OT_SAVE_TEMPS;
192     } else if (opt == "disable-output") {
193       TheOutputType = OT_DISABLE;
194     } else if (opt == "thinlto") {
195       thinlto = true;
196     } else if (opt == "thinlto-index-only") {
197       thinlto_index_only = true;
198     } else if (opt.startswith("thinlto-index-only=")) {
199       thinlto_index_only = true;
200       thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
201     } else if (opt == "thinlto-emit-imports-files") {
202       thinlto_emit_imports_files = true;
203     } else if (opt.startswith("thinlto-prefix-replace=")) {
204       thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
205       if (thinlto_prefix_replace.find(";") == std::string::npos)
206         message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
207     } else if (opt.startswith("cache-dir=")) {
208       cache_dir = opt.substr(strlen("cache-dir="));
209     } else if (opt.size() == 2 && opt[0] == 'O') {
210       if (opt[1] < '0' || opt[1] > '3')
211         message(LDPL_FATAL, "Optimization level must be between 0 and 3");
212       OptLevel = opt[1] - '0';
213     } else if (opt.startswith("jobs=")) {
214       if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
215         message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
216     } else if (opt.startswith("lto-partitions=")) {
217       if (opt.substr(strlen("lto-partitions="))
218               .getAsInteger(10, ParallelCodeGenParallelismLevel))
219         message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
220     } else if (opt == "disable-verify") {
221       DisableVerify = true;
222     } else {
223       // Save this option to pass to the code generator.
224       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
225       // add that.
226       if (extra.empty())
227         extra.push_back("LLVMgold");
228 
229       extra.push_back(opt_);
230     }
231   }
232 }
233 
234 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
235                                         int *claimed);
236 static ld_plugin_status all_symbols_read_hook(void);
237 static ld_plugin_status cleanup_hook(void);
238 
239 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
240 ld_plugin_status onload(ld_plugin_tv *tv) {
241   InitializeAllTargetInfos();
242   InitializeAllTargets();
243   InitializeAllTargetMCs();
244   InitializeAllAsmParsers();
245   InitializeAllAsmPrinters();
246 
247   // We're given a pointer to the first transfer vector. We read through them
248   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
249   // contain pointers to functions that we need to call to register our own
250   // hooks. The others are addresses of functions we can use to call into gold
251   // for services.
252 
253   bool registeredClaimFile = false;
254   bool RegisteredAllSymbolsRead = false;
255 
256   for (; tv->tv_tag != LDPT_NULL; ++tv) {
257     // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
258     // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
259     // header.
260     switch (static_cast<int>(tv->tv_tag)) {
261     case LDPT_OUTPUT_NAME:
262       output_name = tv->tv_u.tv_string;
263       break;
264     case LDPT_LINKER_OUTPUT:
265       switch (tv->tv_u.tv_val) {
266       case LDPO_REL: // .o
267       case LDPO_DYN: // .so
268         IsExecutable = false;
269         RelocationModel = Reloc::PIC_;
270         break;
271       case LDPO_PIE: // position independent executable
272         IsExecutable = true;
273         RelocationModel = Reloc::PIC_;
274         break;
275       case LDPO_EXEC: // .exe
276         IsExecutable = true;
277         RelocationModel = Reloc::Static;
278         break;
279       default:
280         message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
281         return LDPS_ERR;
282       }
283       break;
284     case LDPT_OPTION:
285       options::process_plugin_option(tv->tv_u.tv_string);
286       break;
287     case LDPT_REGISTER_CLAIM_FILE_HOOK: {
288       ld_plugin_register_claim_file callback;
289       callback = tv->tv_u.tv_register_claim_file;
290 
291       if (callback(claim_file_hook) != LDPS_OK)
292         return LDPS_ERR;
293 
294       registeredClaimFile = true;
295     } break;
296     case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
297       ld_plugin_register_all_symbols_read callback;
298       callback = tv->tv_u.tv_register_all_symbols_read;
299 
300       if (callback(all_symbols_read_hook) != LDPS_OK)
301         return LDPS_ERR;
302 
303       RegisteredAllSymbolsRead = true;
304     } break;
305     case LDPT_REGISTER_CLEANUP_HOOK: {
306       ld_plugin_register_cleanup callback;
307       callback = tv->tv_u.tv_register_cleanup;
308 
309       if (callback(cleanup_hook) != LDPS_OK)
310         return LDPS_ERR;
311     } break;
312     case LDPT_GET_INPUT_FILE:
313       get_input_file = tv->tv_u.tv_get_input_file;
314       break;
315     case LDPT_RELEASE_INPUT_FILE:
316       release_input_file = tv->tv_u.tv_release_input_file;
317       break;
318     case LDPT_ADD_SYMBOLS:
319       add_symbols = tv->tv_u.tv_add_symbols;
320       break;
321     case LDPT_GET_SYMBOLS_V2:
322       // Do not override get_symbols_v3 with get_symbols_v2.
323       if (!get_symbols)
324         get_symbols = tv->tv_u.tv_get_symbols;
325       break;
326     case LDPT_GET_SYMBOLS_V3:
327       get_symbols = tv->tv_u.tv_get_symbols;
328       break;
329     case LDPT_ADD_INPUT_FILE:
330       add_input_file = tv->tv_u.tv_add_input_file;
331       break;
332     case LDPT_SET_EXTRA_LIBRARY_PATH:
333       set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
334       break;
335     case LDPT_GET_VIEW:
336       get_view = tv->tv_u.tv_get_view;
337       break;
338     case LDPT_MESSAGE:
339       message = tv->tv_u.tv_message;
340       break;
341     default:
342       break;
343     }
344   }
345 
346   if (!registeredClaimFile) {
347     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
348     return LDPS_ERR;
349   }
350   if (!add_symbols) {
351     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
352     return LDPS_ERR;
353   }
354 
355   if (!RegisteredAllSymbolsRead)
356     return LDPS_OK;
357 
358   if (!get_input_file) {
359     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
360     return LDPS_ERR;
361   }
362   if (!release_input_file) {
363     message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
364     return LDPS_ERR;
365   }
366 
367   return LDPS_OK;
368 }
369 
370 static void diagnosticHandler(const DiagnosticInfo &DI) {
371   if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
372     std::error_code EC = BDI->getError();
373     if (EC == BitcodeError::InvalidBitcodeSignature)
374       return;
375   }
376 
377   std::string ErrStorage;
378   {
379     raw_string_ostream OS(ErrStorage);
380     DiagnosticPrinterRawOStream DP(OS);
381     DI.print(DP);
382   }
383   ld_plugin_level Level;
384   switch (DI.getSeverity()) {
385   case DS_Error:
386     message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
387             ErrStorage.c_str());
388   case DS_Warning:
389     Level = LDPL_WARNING;
390     break;
391   case DS_Note:
392   case DS_Remark:
393     Level = LDPL_INFO;
394     break;
395   }
396   message(Level, "LLVM gold plugin: %s",  ErrStorage.c_str());
397 }
398 
399 static void check(Error E, std::string Msg = "LLVM gold plugin") {
400   handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
401     message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
402     return Error::success();
403   });
404 }
405 
406 template <typename T> static T check(Expected<T> E) {
407   if (E)
408     return std::move(*E);
409   check(E.takeError());
410   return T();
411 }
412 
413 /// Called by gold to see whether this file is one that our plugin can handle.
414 /// We'll try to open it and register all the symbols with add_symbol if
415 /// possible.
416 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
417                                         int *claimed) {
418   MemoryBufferRef BufferRef;
419   std::unique_ptr<MemoryBuffer> Buffer;
420   if (get_view) {
421     const void *view;
422     if (get_view(file->handle, &view) != LDPS_OK) {
423       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
424       return LDPS_ERR;
425     }
426     BufferRef =
427         MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
428   } else {
429     int64_t offset = 0;
430     // Gold has found what might be IR part-way inside of a file, such as
431     // an .a archive.
432     if (file->offset) {
433       offset = file->offset;
434     }
435     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
436         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
437                                        offset);
438     if (std::error_code EC = BufferOrErr.getError()) {
439       message(LDPL_ERROR, EC.message().c_str());
440       return LDPS_ERR;
441     }
442     Buffer = std::move(BufferOrErr.get());
443     BufferRef = Buffer->getMemBufferRef();
444   }
445 
446   *claimed = 1;
447 
448   Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
449   if (!ObjOrErr) {
450     handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
451       std::error_code EC = EI.convertToErrorCode();
452       if (EC == object::object_error::invalid_file_type ||
453           EC == object::object_error::bitcode_section_not_found)
454         *claimed = 0;
455       else
456         message(LDPL_ERROR,
457                 "LLVM gold plugin has failed to create LTO module: %s",
458                 EI.message().c_str());
459     });
460 
461     return *claimed ? LDPS_ERR : LDPS_OK;
462   }
463 
464   std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
465 
466   Modules.resize(Modules.size() + 1);
467   claimed_file &cf = Modules.back();
468 
469   cf.handle = file->handle;
470   // Keep track of the first handle for each file descriptor, since there are
471   // multiple in the case of an archive. This is used later in the case of
472   // ThinLTO parallel backends to ensure that each file is only opened and
473   // released once.
474   auto LeaderHandle =
475       FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
476   cf.leader_handle = LeaderHandle->second;
477   // Save the filesize since for parallel ThinLTO backends we can only
478   // invoke get_input_file once per archive (only for the leader handle).
479   cf.filesize = file->filesize;
480   // In the case of an archive library, all but the first member must have a
481   // non-zero offset, which we can append to the file name to obtain a
482   // unique name.
483   cf.name = file->name;
484   if (file->offset)
485     cf.name += ".llvm." + std::to_string(file->offset) + "." +
486                sys::path::filename(Obj->getSourceFileName()).str();
487 
488   for (auto &Sym : Obj->symbols()) {
489     uint32_t Symflags = Sym.getFlags();
490 
491     cf.syms.push_back(ld_plugin_symbol());
492     ld_plugin_symbol &sym = cf.syms.back();
493     sym.version = nullptr;
494     StringRef Name = Sym.getName();
495     sym.name = strdup(Name.str().c_str());
496 
497     ResolutionInfo &Res = ResInfo[Name];
498 
499     Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
500 
501     sym.visibility = LDPV_DEFAULT;
502     GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
503     if (Vis != GlobalValue::DefaultVisibility)
504       Res.DefaultVisibility = false;
505     switch (Vis) {
506     case GlobalValue::DefaultVisibility:
507       break;
508     case GlobalValue::HiddenVisibility:
509       sym.visibility = LDPV_HIDDEN;
510       break;
511     case GlobalValue::ProtectedVisibility:
512       sym.visibility = LDPV_PROTECTED;
513       break;
514     }
515 
516     if (Symflags & object::BasicSymbolRef::SF_Undefined) {
517       sym.def = LDPK_UNDEF;
518       if (Symflags & object::BasicSymbolRef::SF_Weak)
519         sym.def = LDPK_WEAKUNDEF;
520     } else if (Symflags & object::BasicSymbolRef::SF_Common)
521       sym.def = LDPK_COMMON;
522     else if (Symflags & object::BasicSymbolRef::SF_Weak)
523       sym.def = LDPK_WEAKDEF;
524     else
525       sym.def = LDPK_DEF;
526 
527     sym.size = 0;
528     sym.comdat_key = nullptr;
529     const Comdat *C = check(Sym.getComdat());
530     if (C)
531       sym.comdat_key = strdup(C->getName().str().c_str());
532 
533     sym.resolution = LDPR_UNKNOWN;
534   }
535 
536   if (!cf.syms.empty()) {
537     if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
538       message(LDPL_ERROR, "Unable to add symbols!");
539       return LDPS_ERR;
540     }
541   }
542 
543   return LDPS_OK;
544 }
545 
546 static void freeSymName(ld_plugin_symbol &Sym) {
547   free(Sym.name);
548   free(Sym.comdat_key);
549   Sym.name = nullptr;
550   Sym.comdat_key = nullptr;
551 }
552 
553 /// Helper to get a file's symbols and a view into it via gold callbacks.
554 static const void *getSymbolsAndView(claimed_file &F) {
555   ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
556   if (status == LDPS_NO_SYMS)
557     return nullptr;
558 
559   if (status != LDPS_OK)
560     message(LDPL_FATAL, "Failed to get symbol information");
561 
562   const void *View;
563   if (get_view(F.handle, &View) != LDPS_OK)
564     message(LDPL_FATAL, "Failed to get a view of file");
565 
566   return View;
567 }
568 
569 static void addModule(LTO &Lto, claimed_file &F, const void *View) {
570   MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize), F.name);
571   Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
572 
573   if (!ObjOrErr)
574     message(LDPL_FATAL, "Could not read bitcode from file : %s",
575             toString(ObjOrErr.takeError()).c_str());
576 
577   unsigned SymNum = 0;
578   std::vector<SymbolResolution> Resols(F.syms.size());
579   for (ld_plugin_symbol &Sym : F.syms) {
580     SymbolResolution &R = Resols[SymNum++];
581 
582     ld_plugin_symbol_resolution Resolution =
583         (ld_plugin_symbol_resolution)Sym.resolution;
584 
585     ResolutionInfo &Res = ResInfo[Sym.name];
586 
587     switch (Resolution) {
588     case LDPR_UNKNOWN:
589       llvm_unreachable("Unexpected resolution");
590 
591     case LDPR_RESOLVED_IR:
592     case LDPR_RESOLVED_EXEC:
593     case LDPR_RESOLVED_DYN:
594     case LDPR_PREEMPTED_IR:
595     case LDPR_PREEMPTED_REG:
596     case LDPR_UNDEF:
597       break;
598 
599     case LDPR_PREVAILING_DEF_IRONLY:
600       R.Prevailing = true;
601       break;
602 
603     case LDPR_PREVAILING_DEF:
604       R.Prevailing = true;
605       R.VisibleToRegularObj = true;
606       break;
607 
608     case LDPR_PREVAILING_DEF_IRONLY_EXP:
609       R.Prevailing = true;
610       if (!Res.CanOmitFromDynSym)
611         R.VisibleToRegularObj = true;
612       break;
613     }
614 
615     if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
616         (IsExecutable || !Res.DefaultVisibility))
617       R.FinalDefinitionInLinkageUnit = true;
618 
619     freeSymName(Sym);
620   }
621 
622   check(Lto.add(std::move(*ObjOrErr), Resols),
623         std::string("Failed to link module ") + F.name);
624 }
625 
626 static void recordFile(std::string Filename, bool TempOutFile) {
627   if (add_input_file(Filename.c_str()) != LDPS_OK)
628     message(LDPL_FATAL,
629             "Unable to add .o file to the link. File left behind in: %s",
630             Filename.c_str());
631   if (TempOutFile)
632     Cleanup.push_back(Filename.c_str());
633 }
634 
635 /// Return the desired output filename given a base input name, a flag
636 /// indicating whether a temp file should be generated, and an optional task id.
637 /// The new filename generated is returned in \p NewFilename.
638 static void getOutputFileName(SmallString<128> InFilename, bool TempOutFile,
639                               SmallString<128> &NewFilename, int TaskID = -1) {
640   if (TempOutFile) {
641     std::error_code EC =
642         sys::fs::createTemporaryFile("lto-llvm", "o", NewFilename);
643     if (EC)
644       message(LDPL_FATAL, "Could not create temporary file: %s",
645               EC.message().c_str());
646   } else {
647     NewFilename = InFilename;
648     if (TaskID >= 0)
649       NewFilename += utostr(TaskID);
650   }
651 }
652 
653 static CodeGenOpt::Level getCGOptLevel() {
654   switch (options::OptLevel) {
655   case 0:
656     return CodeGenOpt::None;
657   case 1:
658     return CodeGenOpt::Less;
659   case 2:
660     return CodeGenOpt::Default;
661   case 3:
662     return CodeGenOpt::Aggressive;
663   }
664   llvm_unreachable("Invalid optimization level");
665 }
666 
667 /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
668 /// \p NewPrefix strings, if it was specified.
669 static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
670                                       std::string &NewPrefix) {
671   StringRef PrefixReplace = options::thinlto_prefix_replace;
672   assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
673   std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
674   OldPrefix = Split.first.str();
675   NewPrefix = Split.second.str();
676 }
677 
678 static std::unique_ptr<LTO> createLTO() {
679   Config Conf;
680   ThinBackend Backend;
681 
682   Conf.CPU = options::mcpu;
683   Conf.Options = InitTargetOptionsFromCodeGenFlags();
684 
685   // Disable the new X86 relax relocations since gold might not support them.
686   // FIXME: Check the gold version or add a new option to enable them.
687   Conf.Options.RelaxELFRelocations = false;
688 
689   Conf.MAttrs = MAttrs;
690   Conf.RelocModel = *RelocationModel;
691   Conf.CGOptLevel = getCGOptLevel();
692   Conf.DisableVerify = options::DisableVerify;
693   Conf.OptLevel = options::OptLevel;
694   if (options::Parallelism)
695     Backend = createInProcessThinBackend(options::Parallelism);
696   if (options::thinlto_index_only) {
697     std::string OldPrefix, NewPrefix;
698     getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
699     Backend = createWriteIndexesThinBackend(
700         OldPrefix, NewPrefix, options::thinlto_emit_imports_files,
701         options::thinlto_linked_objects_file);
702   }
703 
704   Conf.OverrideTriple = options::triple;
705   Conf.DefaultTriple = sys::getDefaultTargetTriple();
706 
707   Conf.DiagHandler = diagnosticHandler;
708 
709   switch (options::TheOutputType) {
710   case options::OT_NORMAL:
711     break;
712 
713   case options::OT_DISABLE:
714     Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
715     break;
716 
717   case options::OT_BC_ONLY:
718     Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
719       std::error_code EC;
720       raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
721       if (EC)
722         message(LDPL_FATAL, "Failed to write the output file.");
723       WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
724       return false;
725     };
726     break;
727 
728   case options::OT_SAVE_TEMPS:
729     check(Conf.addSaveTemps(output_name + ".",
730                             /* UseInputModulePath */ true));
731     break;
732   }
733 
734   return llvm::make_unique<LTO>(std::move(Conf), Backend,
735                                 options::ParallelCodeGenParallelismLevel);
736 }
737 
738 // Write empty files that may be expected by a distributed build
739 // system when invoked with thinlto_index_only. This is invoked when
740 // the linker has decided not to include the given module in the
741 // final link. Frequently the distributed build system will want to
742 // confirm that all expected outputs are created based on all of the
743 // modules provided to the linker.
744 static void writeEmptyDistributedBuildOutputs(std::string &ModulePath,
745                                               std::string &OldPrefix,
746                                               std::string &NewPrefix) {
747   std::string NewModulePath =
748       getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
749   std::error_code EC;
750   {
751     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
752                       sys::fs::OpenFlags::F_None);
753     if (EC)
754       message(LDPL_FATAL, "Failed to write '%s': %s",
755               (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
756   }
757   if (options::thinlto_emit_imports_files) {
758     raw_fd_ostream OS(NewModulePath + ".imports", EC,
759                       sys::fs::OpenFlags::F_None);
760     if (EC)
761       message(LDPL_FATAL, "Failed to write '%s': %s",
762               (NewModulePath + ".imports").c_str(), EC.message().c_str());
763   }
764 }
765 
766 /// gold informs us that all symbols have been read. At this point, we use
767 /// get_symbols to see if any of our definitions have been overridden by a
768 /// native object file. Then, perform optimization and codegen.
769 static ld_plugin_status allSymbolsReadHook() {
770   if (Modules.empty())
771     return LDPS_OK;
772 
773   if (unsigned NumOpts = options::extra.size())
774     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
775 
776   // Map to own RAII objects that manage the file opening and releasing
777   // interfaces with gold. This is needed only for ThinLTO mode, since
778   // unlike regular LTO, where addModule will result in the opened file
779   // being merged into a new combined module, we need to keep these files open
780   // through Lto->run().
781   DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
782 
783   std::unique_ptr<LTO> Lto = createLTO();
784 
785   std::string OldPrefix, NewPrefix;
786   if (options::thinlto_index_only)
787     getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
788 
789   for (claimed_file &F : Modules) {
790     if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
791       HandleToInputFile.insert(std::make_pair(
792           F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
793     const void *View = getSymbolsAndView(F);
794     if (!View) {
795       if (options::thinlto_index_only)
796         // Write empty output files that may be expected by the distributed
797         // build system.
798         writeEmptyDistributedBuildOutputs(F.name, OldPrefix, NewPrefix);
799       continue;
800     }
801     addModule(*Lto, F, View);
802   }
803 
804   SmallString<128> Filename;
805   // Note that getOutputFileName will append a unique ID for each task
806   if (!options::obj_path.empty())
807     Filename = options::obj_path;
808   else if (options::TheOutputType == options::OT_SAVE_TEMPS)
809     Filename = output_name + ".o";
810   bool SaveTemps = !Filename.empty();
811 
812   MaxTasks = Lto->getMaxTasks();
813   std::vector<uintptr_t> IsTemporary(MaxTasks);
814   std::vector<SmallString<128>> Filenames(MaxTasks);
815 
816   auto AddStream =
817       [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
818     IsTemporary[Task] = !SaveTemps;
819     getOutputFileName(Filename, /*TempOutFile=*/!SaveTemps, Filenames[Task],
820                       MaxTasks > 1 ? Task : -1);
821     int FD;
822     std::error_code EC =
823         sys::fs::openFileForWrite(Filenames[Task], FD, sys::fs::F_None);
824     if (EC)
825       message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
826     return llvm::make_unique<lto::NativeObjectStream>(
827         llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
828   };
829 
830   auto AddFile = [&](size_t Task, StringRef Path) { Filenames[Task] = Path; };
831 
832   NativeObjectCache Cache;
833   if (!options::cache_dir.empty())
834     Cache = localCache(options::cache_dir, AddFile);
835 
836   check(Lto->run(AddStream, Cache));
837 
838   if (options::TheOutputType == options::OT_DISABLE ||
839       options::TheOutputType == options::OT_BC_ONLY)
840     return LDPS_OK;
841 
842   if (options::thinlto_index_only) {
843     cleanup_hook();
844     exit(0);
845   }
846 
847   for (unsigned I = 0; I != MaxTasks; ++I)
848     if (!Filenames[I].empty())
849       recordFile(Filenames[I].str(), IsTemporary[I]);
850 
851   if (!options::extra_library_path.empty() &&
852       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
853     message(LDPL_FATAL, "Unable to set the extra library path.");
854 
855   return LDPS_OK;
856 }
857 
858 static ld_plugin_status all_symbols_read_hook(void) {
859   ld_plugin_status Ret = allSymbolsReadHook();
860   llvm_shutdown();
861 
862   if (options::TheOutputType == options::OT_BC_ONLY ||
863       options::TheOutputType == options::OT_DISABLE) {
864     if (options::TheOutputType == options::OT_DISABLE) {
865       // Remove the output file here since ld.bfd creates the output file
866       // early.
867       std::error_code EC = sys::fs::remove(output_name);
868       if (EC)
869         message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
870                 EC.message().c_str());
871     }
872     exit(0);
873   }
874 
875   return Ret;
876 }
877 
878 static ld_plugin_status cleanup_hook(void) {
879   for (std::string &Name : Cleanup) {
880     std::error_code EC = sys::fs::remove(Name);
881     if (EC)
882       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
883               EC.message().c_str());
884   }
885 
886   return LDPS_OK;
887 }
888