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